From 3853ca2f1c4a2704ddfb91ae0de9e75d7a78004f Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:59:51 +0100 Subject: [PATCH] refactor: public names for cross-module reads --- scripts/acquire/history.py | 4 +- scripts/build_installer.py | 7 +- scripts/check_freshness.py | 18 +-- scripts/core/anchors.py | 2 +- scripts/core/artifacts.py | 2 +- scripts/core/crypto_verify.py | 6 +- scripts/core/deterministic_zip.py | 4 +- scripts/core/gitclone.py | 10 +- scripts/core/sect233r1.py | 24 +-- scripts/core/upstream.py | 92 ++++++------ scripts/cross_reference.py | 4 +- scripts/dedup.py | 4 +- scripts/devtools/prchecks.py | 5 +- scripts/exporter/doubled.py | 10 +- scripts/exporter/emudeck_exporter.py | 14 +- scripts/exporter/landed.py | 16 +- scripts/exporter/romm_exporter.py | 6 +- scripts/fetch_site_images.py | 8 +- scripts/generate_pack.py | 46 +++--- scripts/generate_readme.py | 4 +- scripts/generate_site.py | 4 +- scripts/installer_build/amalgamate.py | 2 - scripts/installer_build/eventschema.py | 7 +- scripts/installer_build/installerdoc.py | 19 ++- scripts/installer_build/launcherindex.py | 4 +- scripts/installer_build/pins.py | 7 +- scripts/installer_build/port.py | 14 +- scripts/installer_build/pypi.py | 15 +- scripts/make_og_cards.py | 6 +- scripts/mame_ref_audit.py | 4 +- scripts/model/collection.py | 26 ++-- scripts/model/nodedup.py | 2 +- scripts/model/profiles.py | 20 +-- scripts/model/region.py | 8 +- scripts/model/registry.py | 2 +- scripts/model/romfolders.py | 12 +- scripts/model/siteinputs.py | 8 +- scripts/model/sourceref.py | 12 +- scripts/model/systemnames.py | 64 ++++---- scripts/model/systems.py | 12 +- scripts/packs/archive.py | 30 ++-- scripts/packs/coverage.py | 28 ++-- scripts/packs/crossref.py | 30 ++-- scripts/packs/datadirs.py | 10 +- scripts/packs/datatrees.py | 36 ++--- scripts/packs/emulatorcheck.py | 42 +++--- scripts/packs/emulatorpack.py | 58 ++++---- scripts/packs/extras.py | 74 +++++----- scripts/packs/finalize.py | 20 +-- scripts/packs/gaps.py | 16 +- scripts/packs/integrity.py | 16 +- scripts/packs/manifest.py | 86 +++++------ scripts/packs/manifestcores.py | 74 +++++----- scripts/packs/manifestentry.py | 34 ++--- scripts/packs/manifestselect.py | 14 +- scripts/packs/md5pack.py | 16 +- scripts/packs/naming.py | 50 +++---- scripts/packs/paths.py | 12 +- scripts/packs/platformpack.py | 110 +++++++------- scripts/packs/readme.py | 10 +- scripts/packs/report.py | 20 +-- scripts/packs/slots.py | 20 +-- scripts/packs/standalone.py | 8 +- scripts/packs/verdicts.py | 8 +- scripts/pipeline.py | 20 +-- scripts/probes/packprobe.py | 10 +- scripts/profile_sync.py | 30 ++-- scripts/profiling/citations.py | 12 +- scripts/profiling/detection.py | 12 +- scripts/profiling/proseedit.py | 10 +- scripts/profiling/realign.py | 12 +- scripts/profiling/rebase.py | 32 ++-- scripts/profiling/reports.py | 10 +- scripts/profiling/repos.py | 2 +- scripts/profiling/resolver.py | 10 +- scripts/profiling/run.py | 26 ++-- scripts/profiling/triage.py | 14 +- scripts/profiling/versions.py | 4 +- scripts/release/record.py | 2 +- scripts/resolve/archives.py | 6 +- scripts/resolve/categories.py | 28 ++-- scripts/resolve/collisions.py | 16 +- scripts/resolve/contentlayout.py | 30 ++-- scripts/resolve/cores.py | 8 +- scripts/resolve/datadirs.py | 4 +- scripts/resolve/launchers.py | 16 +- scripts/resolve/layout.py | 6 +- scripts/resolve/localfile.py | 76 +++++----- scripts/resolve/ownership.py | 26 ++-- scripts/resolve/packfiles.py | 16 +- scripts/resolve/reconcile.py | 52 +++---- scripts/resolve/review.py | 4 +- scripts/resolve/standalone.py | 16 +- scripts/resolve/truth.py | 16 +- scripts/resolve/validation.py | 6 +- scripts/romrecipes/build.py | 6 +- scripts/romrecipes/capture.py | 6 +- scripts/romrecipes/members.py | 4 +- scripts/scraper/buildbot_system.py | 4 +- scripts/scraper/emudeck_scraper.py | 10 +- scripts/scraper/game_dat_importer.py | 8 +- scripts/scraper/mame_parser.py | 4 +- scripts/scraper/romfolders/__init__.py | 4 +- scripts/sitegen/apiitems.py | 22 +-- scripts/sitegen/build.py | 123 ++++++++-------- scripts/sitegen/cards.py | 97 ++++++------ scripts/sitegen/config.py | 8 +- scripts/sitegen/consolecards.py | 54 +++---- scripts/sitegen/crossref.py | 36 ++--- scripts/sitegen/dataexports.py | 57 +++---- scripts/sitegen/datapage.py | 17 ++- scripts/sitegen/decorate.py | 23 +-- scripts/sitegen/descriptions.py | 16 +- scripts/sitegen/diagrams.py | 114 +++++++------- scripts/sitegen/emulatorcards.py | 166 ++++++++++----------- scripts/sitegen/emulatorpage.py | 168 ++++++++++----------- scripts/sitegen/emulatorsindex.py | 6 +- scripts/sitegen/fields.py | 26 ++-- scripts/sitegen/gaps.py | 66 ++++----- scripts/sitegen/getpages.py | 37 ++--- scripts/sitegen/guidepage.py | 50 +++---- scripts/sitegen/home.py | 24 +-- scripts/sitegen/install.py | 56 +++---- scripts/sitegen/lookup.py | 69 ++++----- scripts/sitegen/measurements.py | 9 +- scripts/sitegen/nav.py | 14 +- scripts/sitegen/pagemarkdown.py | 7 +- scripts/sitegen/parts.py | 24 +-- scripts/sitegen/places.py | 14 +- scripts/sitegen/platformfiles.py | 109 +++++++------- scripts/sitegen/platformindex.py | 4 +- scripts/sitegen/platformpage.py | 68 ++++----- scripts/sitegen/provenance.py | 40 ++--- scripts/sitegen/publish.py | 22 +-- scripts/sitegen/readme.py | 19 ++- scripts/sitegen/reference.py | 6 +- scripts/sitegen/render.py | 105 +++++++------ scripts/sitegen/sources.py | 40 ++--- scripts/sitegen/starlight.py | 10 +- scripts/sitegen/startwith.py | 156 ++++++++++---------- scripts/sitegen/steps.py | 70 ++++----- scripts/sitegen/structured.py | 25 ++-- scripts/sitegen/systempages.py | 107 +++++++------- scripts/sitegen/systemsindex.py | 34 ++--- scripts/sitegen/versions.py | 4 +- scripts/sitegen/wanted.py | 4 +- scripts/sitegen/whichpack.py | 26 ++-- scripts/sitegen/write.py | 14 +- scripts/validate_pr.py | 12 +- scripts/verify.py | 14 +- tests/test_agnostic_scan.py | 8 +- tests/test_agnostic_scan_mode.py | 4 +- tests/test_archive_choice.py | 4 +- tests/test_atomic_artifacts.py | 6 +- tests/test_audit_regressions.py | 134 ++++++++--------- tests/test_case_insensitive_platforms.py | 12 +- tests/test_check_freshness.py | 2 +- tests/test_content_checks.py | 12 +- tests/test_core_data_trees.py | 2 +- tests/test_core_file_fills_declaration.py | 24 +-- tests/test_core_size_refusal.py | 8 +- tests/test_cross_reference_sources.py | 4 +- tests/test_crypto_unique_data.py | 10 +- tests/test_crypto_verify.py | 36 ++--- tests/test_dedup.py | 6 +- tests/test_deterministic_zip.py | 24 +-- tests/test_directory_entries.py | 8 +- tests/test_doc_pages.py | 2 +- tests/test_e2e.py | 172 +++++++++++----------- tests/test_emulator_pack_counts.py | 4 +- tests/test_export_report.py | 4 +- tests/test_extra_identity.py | 10 +- tests/test_find_pinned_revision.py | 2 +- tests/test_foreign_tree.py | 6 +- tests/test_game_data_homonyms.py | 4 +- tests/test_hashing.py | 4 +- tests/test_hidden_extras.py | 2 +- tests/test_install_cores.py | 8 +- tests/test_install_selection.py | 18 +-- tests/test_launcher_gaps.py | 4 +- tests/test_launcher_layer.py | 20 +-- tests/test_launcher_placement.py | 12 +- tests/test_libretro_layout.py | 12 +- tests/test_maker_folder_names.py | 6 +- tests/test_mame_devices.py | 6 +- tests/test_manifest_entry.py | 2 +- tests/test_md5_pack_context.py | 6 +- tests/test_minui_platform.py | 4 +- tests/test_native_mode.py | 12 +- tests/test_no_game_data.py | 6 +- tests/test_pack_conformance_dirs.py | 4 +- tests/test_pack_core_extras.py | 8 +- tests/test_pack_counts.py | 10 +- tests/test_pack_destinations.py | 12 +- tests/test_pack_file_names.py | 6 +- tests/test_pack_integrity.py | 4 +- tests/test_pack_readme.py | 12 +- tests/test_path_conflict_status.py | 20 +-- tests/test_path_null_copies.py | 4 +- tests/test_profile_checks.py | 4 +- tests/test_profile_sync.py | 94 ++++++------ tests/test_pypi_package.py | 6 +- tests/test_refresh_data_dirs.py | 22 +-- tests/test_region.py | 32 ++-- tests/test_region_held.py | 4 +- tests/test_release_packs.py | 2 +- tests/test_required_only_twins.py | 4 +- tests/test_save_root.py | 12 +- tests/test_scraper_contract.py | 18 +-- tests/test_site_arcade_boards.py | 2 +- tests/test_site_availability.py | 12 +- tests/test_site_bootstrap.py | 4 +- tests/test_site_content_data.py | 2 +- tests/test_site_cores.py | 2 +- tests/test_site_density_cards.py | 16 +- tests/test_site_emulator_page.py | 4 +- tests/test_site_emulators.py | 34 ++--- tests/test_site_entry.py | 32 ++-- tests/test_site_exports.py | 76 +++++----- tests/test_site_funnel.py | 4 +- tests/test_site_handheld.py | 6 +- tests/test_site_inputs.py | 12 +- tests/test_site_integration.py | 12 +- tests/test_site_nav.py | 8 +- tests/test_site_platform_density.py | 6 +- tests/test_site_platform_hashes.py | 4 +- tests/test_site_reference.py | 42 +++--- tests/test_site_render.py | 18 +-- tests/test_site_search.py | 32 ++-- tests/test_site_system_links.py | 42 +++--- tests/test_site_system_names.py | 8 +- tests/test_site_system_sections.py | 20 +-- tests/test_site_systems.py | 112 +++++++------- tests/test_site_validation.py | 20 +-- tests/test_site_weight.py | 2 +- tests/test_site_write.py | 30 ++-- tests/test_slots.py | 6 +- tests/test_source_ref_targets.py | 6 +- tests/test_split_pack.py | 6 +- tests/test_system_ids.py | 16 +- tests/test_system_selection.py | 16 +- tests/test_target_names.py | 4 +- tests/test_target_scrapers.py | 2 +- tests/test_target_verify.py | 18 +-- tests/test_twin_declarations.py | 6 +- tests/test_unplaced_extras.py | 20 +-- tests/test_upstream.py | 118 +++++++-------- tests/test_validated_choice.py | 22 +-- tests/test_validation_scope.py | 16 +- tests/test_variant_choice.py | 10 +- tests/test_verify_emulator_evidence.py | 32 ++-- tests/test_verify_pack_choice.py | 14 +- tests/test_verify_release_asset.py | 10 +- tests/test_version_basis.py | 6 +- 254 files changed, 2955 insertions(+), 2969 deletions(-) diff --git a/scripts/acquire/history.py b/scripts/acquire/history.py index acdfd3035..76e7e0cf8 100644 --- a/scripts/acquire/history.py +++ b/scripts/acquire/history.py @@ -31,7 +31,7 @@ def path_history(repo: upstream.Repo, path: str, cache_dir: str) -> list[str]: """Commits that touched a path, newest first.""" shas: list[str] = [] for page in range(1, MAX_PAGES + 1): - payload = upstream._api(_history_url(repo, path, page), cache_dir, False, + payload = upstream.cached_api(_history_url(repo, path, page), cache_dir, False, max_age=upstream.MOVING_TTL) if not isinstance(payload, list) or not payload: break @@ -47,7 +47,7 @@ def find_revision( """The newest revision whose copy of the path has this md5, and its bytes.""" wanted = md5.lower() for sha in path_history(repo, path, cache_dir): - data = upstream._fetch(upstream.content_url(repo, sha, path)) + data = upstream.fetch_body(upstream.content_url(repo, sha, path)) if data is not None and hashlib.md5(data).hexdigest() == wanted: return sha, data return None diff --git a/scripts/build_installer.py b/scripts/build_installer.py index c52bc3fec..64a3b01af 100644 --- a/scripts/build_installer.py +++ b/scripts/build_installer.py @@ -25,7 +25,8 @@ import argparse import sys from core.artifacts import write_text_atomic -from installer_build.amalgamate import BuildError, COMMAND, OUTPUT, PACKAGE, ROOT, build +from installer_build.amalgamate import BuildError, COMMAND, OUTPUT, PACKAGE, build +from core.paths import REPO_ROOT def main(argv: list[str] | None = None) -> int: @@ -34,11 +35,11 @@ def main(argv: list[str] | None = None) -> int: help="write nothing, exit 1 if install.py differs from what the package builds") args = parser.parse_args(argv) try: - text = build(ROOT / PACKAGE) + text = build(REPO_ROOT / PACKAGE) except BuildError as exc: print(f"error: {exc}", file=sys.stderr) return 2 - target = ROOT / OUTPUT + target = REPO_ROOT / OUTPUT current = target.read_text(encoding="utf-8") if target.exists() else "" if args.check: if current != text: diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index dd322c620..64b65803c 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -402,7 +402,7 @@ def check_emulatorjs(platforms_dir: Path, offline: bool) -> Finding: tag = str((yaml_load(fh) or {}).get("version", "")) for path in ROMM_DOCKERFILES: try: - text = upstream._http_text( + text = upstream.http_text( f"https://raw.githubusercontent.com/rommapp/romm/{tag}/{path}") except upstream.UpstreamError as exc: return Finding("platforms", subject, UNKNOWN, local=local, detail=str(exc)) @@ -879,7 +879,7 @@ def core_info_blobs(cache_dir: str, offline: bool) -> dict[str, str] | None: repo = upstream.parse_repo(CORE_INFO_REPO) if repo is None: return None - payload = upstream._api( + payload = upstream.cached_api( f"{repo.api_base}/repos/{repo.slug}/contents?per_page=100", cache_dir, offline, @@ -1097,7 +1097,7 @@ def _game_catalogs(source: str) -> list[dict]: def _no_intro_asset_date(cache_dir: str, offline: bool) -> str: """The day the mirror last rebuilt its No-Intro pack, empty if unlisted.""" repo = upstream.parse_repo(NO_INTRO_MIRROR) - payload = upstream._api( + payload = upstream.cached_api( f"{repo.api_base}/repos/{repo.slug}/releases/tags/{NO_INTRO_RELEASE}", cache_dir, offline, @@ -1149,8 +1149,8 @@ def redump_datfile_version(code: str) -> str: request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "retrobios/1.0"}) with urllib.request.urlopen(request, timeout=60) as response: disposition = response.headers.get("Content-Disposition", "") - named = game_dat_importer._DISPOSITION.search(disposition) - match = game_dat_importer._REDUMP_FILE.match(named["file"]) if named else None + named = game_dat_importer.DISPOSITION.search(disposition) + match = game_dat_importer.REDUMP_FILE.match(named["file"]) if named else None if not match: raise ValueError(f"{url} names no datfile") return f"{match['date']} {match['time']}" @@ -1228,7 +1228,7 @@ def _check_tosec(offline: bool) -> Finding: if offline: return Finding("catalogs", "tosec", SKIPPED, local=imported, detail="offline") try: - html = upstream._http_text(TOSEC_DOWNLOADS) + html = upstream.http_text(TOSEC_DOWNLOADS) except upstream.UpstreamError as exc: return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail=str(exc)) latest = tosec_latest_pack(html or "") @@ -1300,7 +1300,7 @@ def _check_fbneo(cache_dir: str, offline: bool) -> Finding: if offline: return Finding("catalogs", "fbneo recipes", SKIPPED, local=imported, detail="offline") repo = upstream.parse_repo(FBNEO_REPO) - listing = upstream._api( + listing = upstream.cached_api( f"{repo.api_base}/repos/{repo.slug}/contents/dats", cache_dir, offline, @@ -1389,7 +1389,7 @@ def specifier_allows(spec: str, version: str) -> bool: def pypi_latest(name: str) -> str | None: - payload = upstream._http_json(PYPI_URL.format(name=name)) + payload = upstream.http_json(PYPI_URL.format(name=name)) if not isinstance(payload, dict): return None info = payload.get("info") or {} @@ -1406,7 +1406,7 @@ def parse_npm_pins(text: str) -> dict[str, str]: def npm_latest(name: str) -> str | None: - payload = upstream._http_json(NPM_URL.format(name=name)) + payload = upstream.http_json(NPM_URL.format(name=name)) if not isinstance(payload, dict): return None return str(payload.get("version") or "") or None diff --git a/scripts/core/anchors.py b/scripts/core/anchors.py index ad113f7a1..442619e48 100644 --- a/scripts/core/anchors.py +++ b/scripts/core/anchors.py @@ -23,7 +23,7 @@ def toc_slug(text: str) -> str: return re.sub(r"[-\s]+", "-", text) -def _unique(ident: str, used: set[str]) -> str: +def unique_anchor(ident: str, used: set[str]) -> str: while ident in used or not ident: match = IDCOUNT.match(ident) ident = f"{match[1]}_{int(match[2]) + 1}" if match else f"{ident}_1" diff --git a/scripts/core/artifacts.py b/scripts/core/artifacts.py index d032dbe56..facac605b 100644 --- a/scripts/core/artifacts.py +++ b/scripts/core/artifacts.py @@ -355,7 +355,7 @@ def repository_output_lock(path: str) -> contextlib.AbstractContextManager[None] return contextlib.nullcontext() -def _build_timestamp(db: dict | None = None) -> str: +def build_timestamp(db: dict | None = None) -> str: """Timestamp for generated artifacts. Reads the database snapshot the artifact was built from, so rebuilding diff --git a/scripts/core/crypto_verify.py b/scripts/core/crypto_verify.py index 0ecf18438..a3af62621 100644 --- a/scripts/core/crypto_verify.py +++ b/scripts/core/crypto_verify.py @@ -375,7 +375,7 @@ def verify_otp( Returns (valid, reason_string). """ - from core.sect233r1 import _N, _ec_mul, _Gx, _Gy, ecdsa_verify_sha256 + from core.sect233r1 import N, ec_mul, Gx, Gy, ecdsa_verify_sha256 data = bytearray(Path(filepath).read_bytes()) @@ -436,10 +436,10 @@ def verify_otp( signature_rs = bytes(data[0x44:0x80]) # Fix up private key: privkey % subgroup_order (Nintendo's ECC lib quirk) - priv_key_int = int.from_bytes(priv_key_raw, "big") % _N + priv_key_int = int.from_bytes(priv_key_raw, "big") % N # Derive public key from private key: Q = privkey * G - pub_point = _ec_mul(priv_key_int, (_Gx, _Gy)) + pub_point = ec_mul(priv_key_int, (Gx, Gy)) if pub_point is None: return False, "ECC cert: derived public key is point at infinity" pub_key_xy = pub_point[0].to_bytes(30, "big") + pub_point[1].to_bytes(30, "big") diff --git a/scripts/core/deterministic_zip.py b/scripts/core/deterministic_zip.py index e1b60703a..2a4e828e9 100644 --- a/scripts/core/deterministic_zip.py +++ b/scripts/core/deterministic_zip.py @@ -21,7 +21,7 @@ import zipfile from pathlib import Path # Fixed metadata for deterministic ZIPs -_FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp +FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp _FIXED_CREATE_SYSTEM = 0 # FAT/DOS (most compatible) _FIXED_EXTERNAL_ATTR = 0o100644 << 16 # -rw-r--r-- _COMPRESS_LEVEL = 9 # deflate level 9 for determinism @@ -65,7 +65,7 @@ def rebuild_zip_deterministic( ) as dst: for info in entries: out_info = zipfile.ZipInfo( - filename=info.filename, date_time=_FIXED_DATE_TIME + filename=info.filename, date_time=FIXED_DATE_TIME ) out_info.compress_type = zipfile.ZIP_DEFLATED out_info.create_system = _FIXED_CREATE_SYSTEM diff --git a/scripts/core/gitclone.py b/scripts/core/gitclone.py index 4ea3d8db8..c20bcf3aa 100644 --- a/scripts/core/gitclone.py +++ b/scripts/core/gitclone.py @@ -7,7 +7,7 @@ import subprocess -def _git_lines(*args: str) -> list[str] | None: +def git_lines(*args: str) -> list[str] | None: """Output lines of a git command, or None when git refuses it.""" result = subprocess.run(["git", *args], capture_output=True, text=True, check=False) if result.returncode != 0: @@ -27,7 +27,7 @@ def _repo_key(url: str) -> str: return "/".join(re.split(r"[/:]", path)[-2:]).casefold() -def _project_main_line() -> str | None: +def project_main_line() -> str | None: """The project's main line, fetched when this clone does not hold it. A fork's clone has origin alone. Once the commit is pushed to the fork's @@ -37,15 +37,15 @@ def _project_main_line() -> str | None: None leaves the upstream/ and origin/ lines in charge when the clone has no remote at all and only its uncommitted files can be read. """ - remotes = _git_lines("remote") or [] + remotes = git_lines("remote") or [] if not remotes: return None project = {_repo_key(url) for url in PROJECT_URLS} source = PROJECT_URLS[0] for remote in remotes: - urls = _git_lines("remote", "get-url", "--all", remote) or [] + urls = git_lines("remote", "get-url", "--all", remote) or [] if any(_repo_key(url) in project for url in urls): - if _git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"): + if git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"): return f"{remote}/main" source = remote break diff --git a/scripts/core/sect233r1.py b/scripts/core/sect233r1.py index 4e6f7127e..3d553b31e 100644 --- a/scripts/core/sect233r1.py +++ b/scripts/core/sect233r1.py @@ -22,12 +22,12 @@ _F = (1 << 233) | (1 << 74) | 1 # irreducible polynomial _A = 1 _B = 0x0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD -_Gx = 0x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B -_Gy = 0x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052 +Gx = 0x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B +Gy = 0x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052 # Subgroup order -_N = 0x01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7 -_N_BITLEN = _N.bit_length() # 233 +N = 0x01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7 +_N_BITLEN = N.bit_length() # 233 # Cofactor _H = 2 @@ -156,7 +156,7 @@ def _ec_double(p: tuple[int, int] | None) -> tuple[int, int] | None: return (x3, y3) -def _ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None: +def ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None: """Scalar multiplication k*P using double-and-add.""" if k == 0 or p is _INF: return _INF @@ -220,7 +220,7 @@ def ecdsa_verify_sha256( q_point = (qx, qy) # Check r, s in [1, n-1] - if not (1 <= r < _N and 1 <= s < _N): + if not (1 <= r < N and 1 <= s < N): return False h = hashlib.sha256(message).digest() @@ -230,20 +230,20 @@ def ecdsa_verify_sha256( e >>= 256 - _N_BITLEN # w = s^(-1) mod n - w = _modinv(s, _N) + w = _modinv(s, N) # u1 = e*w mod n, u2 = r*w mod n - u1 = (e * w) % _N - u2 = (r * w) % _N + u1 = (e * w) % N + u2 = (r * w) % N # R = u1*G + u2*Q - g_point = (_Gx, _Gy) - r_point = _ec_add(_ec_mul(u1, g_point), _ec_mul(u2, q_point)) + g_point = (Gx, Gy) + r_point = _ec_add(ec_mul(u1, g_point), ec_mul(u2, q_point)) if r_point is _INF: return False # v = R.x (as integer, already in GF(2^m) which is an integer) - v = r_point[0] % _N + v = r_point[0] % N return v == r diff --git a/scripts/core/upstream.py b/scripts/core/upstream.py index 08b14d6bd..96264ce5b 100644 --- a/scripts/core/upstream.py +++ b/scripts/core/upstream.py @@ -311,7 +311,7 @@ def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None: return RATE_LIMIT_WAITS[waited] -def _fetch(url: str, accept_json: bool = False) -> bytes | None: +def fetch_body(url: str, accept_json: bool = False) -> bytes | None: """Body of a GET, or None on 404. A pass over every profile issues thousands of requests, so a dropped @@ -355,15 +355,15 @@ def _fetch(url: str, accept_json: bool = False) -> bytes | None: _sleep(RETRY_BACKOFF[attempt - 1]) -def _http_text(url: str) -> str | None: +def http_text(url: str) -> str | None: """Text body of a GET, or None on 404. Replaced in tests.""" - body = _fetch(url) + body = fetch_body(url) return None if body is None else body.decode("utf-8", errors="replace") -def _http_json(url: str) -> object | None: +def http_json(url: str) -> object | None: """Parsed JSON body of a GET, or None on 404. Replaced in tests.""" - body = _fetch(url, accept_json=True) + body = fetch_body(url, accept_json=True) return None if body is None else json.loads(body.decode()) @@ -419,7 +419,7 @@ def fetch_file( return None if text == ABSENT else text.splitlines() if offline: raise NotCachedError(f"{repo.slug}@{sha[:8]}:{path} is not in the offline cache") - fetched = _http_text(content_url(repo, sha, path)) + fetched = http_text(content_url(repo, sha, path)) write_cache(target, ABSENT if fetched is None else fetched) return None if fetched is None else fetched.splitlines() @@ -441,14 +441,14 @@ def _api_target(url: str, cache_dir: str) -> Path: def _require_cached(url: str, cache_dir: str, offline: bool, what: str) -> None: """Offline, refuse a call the cache holds no answer to, absence included. - _api answers None both for a resource the forge does not have and for + cached_api answers None both for a resource the forge does not have and for one never asked, and only the first is a fact. """ if offline and not _api_target(url, cache_dir).is_file(): raise NotCachedError(f"{what} is not in the offline cache") -def _api( +def cached_api( url: str, cache_dir: str, offline: bool, max_age: float | None = None, absent_max_age: float | None = None, ) -> object | None: @@ -472,7 +472,7 @@ def _api( return None if raw == ABSENT else json.loads(raw) if offline: return None - payload = _http_json(url) + payload = http_json(url) write_cache(target, ABSENT if payload is None else json.dumps(payload)) return payload @@ -492,12 +492,12 @@ def fetch_page(url: str, cache_dir: str, offline: bool) -> str | None: return None if raw == ABSENT else raw if offline: return None - text = _http_text(url) + text = http_text(url) write_cache(target, ABSENT if text is None else text) return text -def _project(repo: Repo) -> str: +def project_path(repo: Repo) -> str: return urllib.parse.quote(f"{repo.owner}/{repo.name}", safe="") @@ -508,7 +508,7 @@ def _commits_url(repo: Repo, date: str | None, branch: str | None = None) -> str base += f"&sha={urllib.parse.quote(branch, safe='')}" elif repo.family == "gitlab": base = ( - f"{repo.api_base}/projects/{_project(repo)}" + f"{repo.api_base}/projects/{project_path(repo)}" f"/repository/commits?per_page=1" ) if branch: @@ -537,10 +537,10 @@ def current_slug(repo: Repo, cache_dir: str, offline: bool = False) -> str | Non name in the payload tells the project moved. """ if repo.family == "gitlab": - url, key = f"{repo.api_base}/projects/{_project(repo)}", "path_with_namespace" + url, key = f"{repo.api_base}/projects/{project_path(repo)}", "path_with_namespace" else: url, key = f"{repo.api_base}/repos/{repo.slug}", "full_name" - payload = _api(url, cache_dir, offline, MOVING_TTL) + payload = cached_api(url, cache_dir, offline, MOVING_TTL) if not isinstance(payload, dict): return None value = payload.get(key) @@ -566,7 +566,7 @@ def resolve_head( _require_cached( url, cache_dir, offline, f"{repo.slug}: tip of {branch or 'the default branch'}" ) - return _first_sha(_api(url, cache_dir, offline, 0 if fresh else MOVING_TTL)) + return _first_sha(cached_api(url, cache_dir, offline, 0 if fresh else MOVING_TTL)) def resolve_commit_at( @@ -581,7 +581,7 @@ def resolve_commit_at( if repo.family in ("github", "gitlab"): url = _commits_url(repo, date, branch) _require_cached(url, cache_dir, offline, f"{repo.slug}: commit at {date}") - return _first_sha(_api(url, cache_dir, offline)) + return _first_sha(cached_api(url, cache_dir, offline)) return _gitea_commit_at(repo, date, cache_dir, offline, branch) @@ -610,7 +610,7 @@ def _gitea_commit_at( while True: url = f"{base}&page={page}" _require_cached(url, cache_dir, offline, f"{repo.slug}: commit at {date}") - payload = _api(url, cache_dir, offline, MOVING_TTL) + payload = cached_api(url, cache_dir, offline, MOVING_TTL) if not isinstance(payload, list) or not payload: return None for entry in payload: @@ -637,7 +637,7 @@ def _gitea_commit_date(entry: object) -> datetime | None: def _tags_url(repo: Repo) -> str: if repo.family == "gitlab": return ( - f"{repo.api_base}/projects/{_project(repo)}" + f"{repo.api_base}/projects/{project_path(repo)}" f"/repository/tags?per_page=100" ) return f"{repo.api_base}/repos/{repo.slug}/tags?per_page=100" @@ -645,7 +645,7 @@ def _tags_url(repo: Repo) -> str: def list_tags(repo: Repo, cache_dir: str, offline: bool = False) -> list[str]: """Tag names, newest first as the forge orders them.""" - payload = _api(_tags_url(repo), cache_dir, offline, MOVING_TTL) + payload = cached_api(_tags_url(repo), cache_dir, offline, MOVING_TTL) if not isinstance(payload, list): return [] return [t["name"] for t in payload if isinstance(t, dict) and t.get("name")] @@ -728,7 +728,7 @@ def resolve_tag_commit( repo: Repo, tag: str, cache_dir: str, offline: bool = False ) -> str | None: """Commit a tag points at.""" - payload = _api(_tags_url(repo), cache_dir, offline, MOVING_TTL) + payload = cached_api(_tags_url(repo), cache_dir, offline, MOVING_TTL) if not isinstance(payload, list): return None for entry in payload: @@ -746,10 +746,10 @@ def _named_tag_commit( """A GitLab or Forgejo tag's commit, asked for by name.""" quoted = urllib.parse.quote(tag, safe="") if repo.family == "gitlab": - url = f"{repo.api_base}/projects/{_project(repo)}/repository/tags/{quoted}" + url = f"{repo.api_base}/projects/{project_path(repo)}/repository/tags/{quoted}" else: url = f"{repo.api_base}/repos/{repo.slug}/tags/{quoted}" - payload = _api(url, cache_dir, offline, absent_max_age=MOVING_TTL) + payload = cached_api(url, cache_dir, offline, absent_max_age=MOVING_TTL) commit = payload.get("commit") if isinstance(payload, dict) else None if not isinstance(commit, dict): return None @@ -772,7 +772,7 @@ def tag_commit( quoted = urllib.parse.quote(tag) # A tag pushed after the first lookup must be seen: the 404 expires, # the commit a tag names does not. - payload = _api( + payload = cached_api( f"{repo.api_base}/repos/{repo.slug}/git/ref/tags/{quoted}", cache_dir, offline, @@ -785,7 +785,7 @@ def tag_commit( return None if obj.get("type") != "tag": return obj.get("sha") - annotated = _api( + annotated = cached_api( f"{repo.api_base}/repos/{repo.slug}/git/tags/{obj.get('sha')}", cache_dir, offline, @@ -796,7 +796,7 @@ def tag_commit( def _releases_url(repo: Repo) -> str: if repo.family == "gitlab": - return f"{repo.api_base}/projects/{_project(repo)}/releases" + return f"{repo.api_base}/projects/{project_path(repo)}/releases" return f"{repo.api_base}/repos/{repo.slug}/releases/latest" @@ -804,7 +804,7 @@ def latest_release( repo: Repo, cache_dir: str, offline: bool = False ) -> Release | None: """Most recent release the forge exposes.""" - payload = _api(_releases_url(repo), cache_dir, offline, MOVING_TTL) + payload = cached_api(_releases_url(repo), cache_dir, offline, MOVING_TTL) if isinstance(payload, list): payload = payload[0] if payload else None if not isinstance(payload, dict): @@ -819,7 +819,7 @@ def latest_release( def _compare_url(repo: Repo, base: str, head: str) -> str: if repo.family == "gitlab": return ( - f"{repo.api_base}/projects/{_project(repo)}" + f"{repo.api_base}/projects/{project_path(repo)}" f"/repository/compare?from={base}&to={head}" ) return f"{repo.api_base}/repos/{repo.slug}/compare/{base}...{head}" @@ -859,7 +859,7 @@ def compare( repo: Repo, base: str, head: str, cache_dir: str, offline: bool = False ) -> CompareResult: """Tree difference between two revisions.""" - payload = _api(_compare_url(repo, base, head), cache_dir, offline) + payload = cached_api(_compare_url(repo, base, head), cache_dir, offline) if not isinstance(payload, dict): return CompareResult([], True) if repo.family == "gitlab": @@ -894,7 +894,7 @@ def fork_base( """ if repo.family != "github" or fork.family != "github": return None - payload = _api( + payload = cached_api( f"{repo.api_base}/repos/{repo.slug}/compare/" f"{sha}...{fork.owner}:{fork.name}:{fork_sha}", cache_dir, offline, @@ -912,7 +912,7 @@ def ancestry( good. GitHub gives both counts in one answer, GitLab and Forgejo list one direction only and are asked twice. """ - forward = _api(_compare_url(repo, base, head), cache_dir, offline) + forward = cached_api(_compare_url(repo, base, head), cache_dir, offline) ahead = _commits_ahead(forward, repo.family) if ahead is None: return None @@ -920,7 +920,7 @@ def ancestry( behind = forward.get("behind_by") if isinstance(forward, dict) else None else: behind = _commits_ahead( - _api(_compare_url(repo, head, base), cache_dir, offline), repo.family + cached_api(_compare_url(repo, head, base), cache_dir, offline), repo.family ) return (ahead, behind) if isinstance(behind, int) else None @@ -951,7 +951,7 @@ def list_directory( if repo.family != "github": return None url = f"{repo.api_base}/repos/{repo.slug}/git/trees/{sha}:{path.strip('/')}" - payload = _api(url, cache_dir, offline) + payload = cached_api(url, cache_dir, offline) if not isinstance(payload, dict) or payload.get("truncated"): return None return sorted( @@ -976,10 +976,10 @@ def _gitlab_tree( paths: list[str] = [] for page in range(1, MAX_TREE_PAGES + 1): url = ( - f"{repo.api_base}/projects/{_project(repo)}/repository/tree" + f"{repo.api_base}/projects/{project_path(repo)}/repository/tree" f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}" ) - payload = _api(url, cache_dir, offline) + payload = cached_api(url, cache_dir, offline) if not isinstance(payload, list): return paths, True paths.extend( @@ -1028,10 +1028,10 @@ def cache_gitlab_directory( def _gitlab_archive_files(repo: Repo, sha: str, directory: str) -> dict[str, str]: url = ( - f"{repo.api_base}/projects/{_project(repo)}/repository/archive.tar.gz" + f"{repo.api_base}/projects/{project_path(repo)}/repository/archive.tar.gz" f"?sha={sha}&path={urllib.parse.quote(directory)}" ) - body = _fetch(url) + body = fetch_body(url) if body is None: return {} prefix = directory + "/" @@ -1084,7 +1084,7 @@ def list_tree( url = _tree_url(repo, sha) if url is None: return [], True - payload = _api(url, cache_dir, offline) + payload = cached_api(url, cache_dir, offline) if not isinstance(payload, dict): return [], True entries = list(payload.get("tree") or []) @@ -1098,7 +1098,7 @@ def list_tree( for page in range(2, MAX_TREE_PAGES + 1): if len(entries) >= total: break - more = _api(f"{url}&page={page}", cache_dir, offline) + more = cached_api(f"{url}&page={page}", cache_dir, offline) if not isinstance(more, dict) or not more.get("tree"): break entries.extend(more["tree"]) @@ -1123,10 +1123,10 @@ def list_gitlinks( links: dict[str, str] = {} for page in range(1, MAX_TREE_PAGES + 1): url = ( - f"{repo.api_base}/projects/{_project(repo)}/repository/tree" + f"{repo.api_base}/projects/{project_path(repo)}/repository/tree" f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}" ) - payload = _api(url, cache_dir, offline) + payload = cached_api(url, cache_dir, offline) if not isinstance(payload, list): break links.update( @@ -1139,7 +1139,7 @@ def list_gitlinks( break return links tree_url = _tree_url(repo, sha) - payload = _api(tree_url, cache_dir, offline) if tree_url else None + payload = cached_api(tree_url, cache_dir, offline) if tree_url else None if not isinstance(payload, dict): return {} return { @@ -1205,8 +1205,8 @@ def through_gitlink( def commit_date(repo: Repo, sha: str, cache_dir: str, offline: bool = False) -> str | None: """When a revision was committed, as the forge reports it (ISO 8601).""" if repo.family == "gitlab": - payload = _api( - f"{repo.api_base}/projects/{_project(repo)}/repository/commits/{sha}", + payload = cached_api( + f"{repo.api_base}/projects/{project_path(repo)}/repository/commits/{sha}", cache_dir, offline, ) value = payload.get("committed_date") if isinstance(payload, dict) else None @@ -1215,7 +1215,7 @@ def commit_date(repo: Repo, sha: str, cache_dir: str, offline: bool = False) -> url = f"{repo.api_base}/repos/{repo.slug}/commits/{sha}" else: url = f"{repo.api_base}/repos/{repo.slug}/git/commits/{sha}" - stamp = _gitea_commit_date(_api(url, cache_dir, offline)) + stamp = _gitea_commit_date(cached_api(url, cache_dir, offline)) return stamp.isoformat() if stamp is not None else None @@ -1238,7 +1238,7 @@ def commits_touching( stamp = urllib.parse.quote(since) if repo.family == "gitlab": url = ( - f"{repo.api_base}/projects/{_project(repo)}" + f"{repo.api_base}/projects/{project_path(repo)}" f"/repository/commits?path={quoted}&since={stamp}&per_page=100" ) elif repo.family == "github": @@ -1253,7 +1253,7 @@ def commits_touching( ) # The list grows with every push touching the path: cached for good, the # triage drift score stayed at whatever the first run counted. - payload = _api(url, cache_dir, offline, MOVING_TTL) + payload = cached_api(url, cache_dir, offline, MOVING_TTL) if not isinstance(payload, list): return 0 return sum( diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index 15a16e196..edb444683 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -35,7 +35,7 @@ from resolve.launchers import ( from packs.crossref import ( DEFAULT_PLATFORMS_DIR, - _build_supplemental_index, + build_supplemental_index, cross_reference, declared_names, folded_declared_slots, @@ -367,7 +367,7 @@ def main() -> None: selected = [args.platform] if args.platform else None declared, plat_data_dirs = load_platform_files(args.platforms_dir, selected) db = load_database(args.db) - data_names = _build_supplemental_index() + data_names = build_supplemental_index() report = cross_reference( profiles, declared, db, plat_data_dirs, data_names, all_declared=declared_names(args.platforms_dir, selected, db), diff --git a/scripts/dedup.py b/scripts/dedup.py index 14cdfbdb3..91b202681 100644 --- a/scripts/dedup.py +++ b/scripts/dedup.py @@ -31,7 +31,7 @@ sys.path.insert(0, os.path.dirname(__file__)) from core.hashing import compute_hashes from core.cli import require_directory from core.artifacts import write_text_atomic -from model.nodedup import _in_nodedup_dir +from model.nodedup import in_nodedup_dir DEFAULT_BIOS_DIR = "bios" @@ -66,7 +66,7 @@ def scan_duplicates(bios_dir: str) -> dict[str, list[str]]: for root, _dirs, files in os.walk(bios_dir): for name in files: path = os.path.join(root, name) - if _in_nodedup_dir(path): + if in_nodedup_dir(path): continue by_size[os.path.getsize(path)].append(path) diff --git a/scripts/devtools/prchecks.py b/scripts/devtools/prchecks.py index a1e7efc4b..f430a7b23 100644 --- a/scripts/devtools/prchecks.py +++ b/scripts/devtools/prchecks.py @@ -11,9 +11,6 @@ from dataclasses import dataclass, field from core.paths import REPO_ROOT -ROOT = REPO_ROOT - - @dataclass(frozen=True) class Step: command: str @@ -72,7 +69,7 @@ def shown(step: Step) -> str: def execute(step: Step) -> int: env = {**os.environ, **step.env} - return subprocess.run(argv(step.command), cwd=ROOT, env=env, check=False).returncode + return subprocess.run(argv(step.command), cwd=REPO_ROOT, env=env, check=False).returncode def run(steps: tuple[Step, ...] = STEPS) -> int: diff --git a/scripts/exporter/doubled.py b/scripts/exporter/doubled.py index 8cfa9d076..256fde3a9 100644 --- a/scripts/exporter/doubled.py +++ b/scripts/exporter/doubled.py @@ -18,8 +18,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from resolve.archives import contents_members, holds_required_members from resolve.standalone import platform_layouts, standalone_set from resolve.cores import resolve_platform_cores -from resolve.reconcile import HASH_FIELDS, _hash_values -from resolve.collisions import _accepted_by_all, _lists_hashes, find_collisions +from resolve.reconcile import HASH_FIELDS, hash_values +from resolve.collisions import accepted_by_all, lists_hashes, find_collisions from resolve.validation import opens_by_name, outside_gap_scope @@ -58,13 +58,13 @@ def _reads(entry: dict, by_name: bool, local: str, db: dict) -> bool: """ if entry.get("contents"): return holds_required_members(local, contents_members(entry)) - if _lists_hashes(entry): - return _accepted_by_all(local, [entry], db) + if lists_hashes(entry): + return accepted_by_all(local, [entry], db) return by_name and _size_fits(entry, local) def _hashes(entry: dict) -> dict[str, list[str]]: - found = {f: _hash_values(entry, f) for f in HASH_FIELDS} + found = {f: hash_values(entry, f) for f in HASH_FIELDS} return {f: values for f, values in found.items() if values} diff --git a/scripts/exporter/emudeck_exporter.py b/scripts/exporter/emudeck_exporter.py index bdfca7f27..9985b936c 100644 --- a/scripts/exporter/emudeck_exporter.py +++ b/scripts/exporter/emudeck_exporter.py @@ -15,10 +15,10 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from scraper.emudeck_scraper import FUNCTION_HASH_MAP, _RE_FUNC, _RE_LOCAL_HASHES +from scraper.emudeck_scraper import FUNCTION_HASH_MAP, RE_FUNC, RE_LOCAL_HASHES from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report, _hash_values +from resolve.reconcile import NativeFile, NativeSystem, Report, hash_values SOURCE_URL = ( "https://raw.githubusercontent.com/dragoonDorise/EmuDeck/main" @@ -80,7 +80,7 @@ class Exporter(BaseExporter[str]): adds nothing, and the truth's extra accepted revisions are not appended: either would grow an array other consumers read too. """ - theirs = _hash_values(fe.platform or {}, "md5") + theirs = hash_values(fe.platform or {}, "md5") if not theirs: return [] if "md5" in fe.corrections: @@ -124,7 +124,7 @@ class Exporter(BaseExporter[str]): if system.native_id == system_id for fe in system.files if "md5" in fe.corrections - for value in _hash_values(fe.platform or {}, "md5") + for value in hash_values(fe.platform or {}, "md5") } @classmethod @@ -146,7 +146,7 @@ class Exporter(BaseExporter[str]): def _function_spans(self, script: str) -> list[tuple[str, int, int]]: """Name and byte span of every check the script defines.""" - matches = list(_RE_FUNC.finditer(script)) + matches = list(RE_FUNC.finditer(script)) spans: list[tuple[str, int, int]] = [] for index, match in enumerate(matches): end = ( @@ -179,7 +179,7 @@ class Exporter(BaseExporter[str]): body = script[start:end] system_id = FUNCTION_HASH_MAP.get(name) md5s = self._md5s(systems, system_id) if system_id else [] - match = _RE_LOCAL_HASHES.search(body) + match = RE_LOCAL_HASHES.search(body) if md5s and match: # An array compared by membership says nothing about order, # so the same set is left as the maintainer wrote it. @@ -226,7 +226,7 @@ class Exporter(BaseExporter[str]): for fname, start, end in self._function_spans(content) if fname == name ) - if not _RE_LOCAL_HASHES.search(body): + if not RE_LOCAL_HASHES.search(body): # A check with no hash list is a path check, not a hash check. continue issues.extend(f"absent from {name}: {md5}" for md5 in md5s if md5 not in body) diff --git a/scripts/exporter/landed.py b/scripts/exporter/landed.py index 7cfd47e06..40572c9c2 100644 --- a/scripts/exporter/landed.py +++ b/scripts/exporter/landed.py @@ -6,7 +6,7 @@ from __future__ import annotations from dataclasses import dataclass, field from .base_exporter import BaseExporter -from resolve.reconcile import HASH_FIELDS, NativeFile, _hash_values, _single_size +from resolve.reconcile import HASH_FIELDS, NativeFile, hash_values, single_size @dataclass @@ -75,7 +75,7 @@ def _change( def _platform_value(entry: NativeFile, field_name: str) -> str | list[str]: - values = _hash_values(entry.platform or {}, field_name) + values = hash_values(entry.platform or {}, field_name) if (entry.platform or {}).get(f"{field_name}_list"): return values return ",".join(values) @@ -157,7 +157,7 @@ def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges: listed is not None and field_name not in entry.corrections and field_name not in entry.filled - and listed != _hash_values(entry.platform, field_name) + and listed != hash_values(entry.platform, field_name) and exporter.states(entry, field_name) ): records.append(_change( @@ -175,28 +175,28 @@ def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges: if ( theirs and ours - and _single_size(theirs) not in (None, ours) + and single_size(theirs) not in (None, ours) and exporter.states(entry, "size") ): records.append(_change( - "size_updated", entry, "size", _single_size(theirs), ours + "size_updated", entry, "size", single_size(theirs), ours )) elif ( theirs and ours is None - and _single_size(theirs) is not None + and single_size(theirs) is not None and exporter.states(entry, "size") ): # The truth took the entry over without a size of its own: # System.dat's neocdz.zip line went out without size 953078. records.append(_change( - "size_removed", entry, "size", _single_size(theirs), None + "size_removed", entry, "size", single_size(theirs), None )) records.extend( _change("hash_cleared", entry, field_name, _platform_value(entry, field_name), None) for field_name in HASH_FIELDS - if _hash_values(entry.platform, field_name) + if hash_values(entry.platform, field_name) and not entry.hashes(field_name) and exporter.clears(entry, field_name) ) diff --git a/scripts/exporter/romm_exporter.py b/scripts/exporter/romm_exporter.py index a22ebcdc4..0c4a7525b 100644 --- a/scripts/exporter/romm_exporter.py +++ b/scripts/exporter/romm_exporter.py @@ -18,7 +18,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from scraper.romm_scraper import SLUG_MAP from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report, _hash_values +from resolve.reconcile import NativeFile, NativeSystem, Report, hash_values SOURCE_URL = ( "https://raw.githubusercontent.com/rommapp/romm/master/backend/models" @@ -161,7 +161,7 @@ class Exporter(BaseExporter[str]): output[key] = OrderedDict( (field, value) for field, name in _FIELDS - if (value := ",".join(_hash_values(fe.platform, name)) + if (value := ",".join(hash_values(fe.platform, name)) if name != "size" else str(fe.platform["size"])) ) continue @@ -185,7 +185,7 @@ class Exporter(BaseExporter[str]): def _contradicted(fe: NativeFile, name: str) -> bool: """A hash the platform states and the truth, taking the entry over, does not keep.""" - return bool(_hash_values(fe.platform or {}, name)) and not fe.hashes(name) + return bool(hash_values(fe.platform or {}, name)) and not fe.hashes(name) def states(self, fe: NativeFile, field_name: str) -> bool: """An entry left whole carries none of the truth's values.""" diff --git a/scripts/fetch_site_images.py b/scripts/fetch_site_images.py index ef6484714..44fc3c529 100644 --- a/scripts/fetch_site_images.py +++ b/scripts/fetch_site_images.py @@ -198,13 +198,13 @@ def fetch_logos() -> None: def fetch_icons() -> None: from model.database import load_database - from model.collection import _group_by_manufacturer - from sitegen.render import SYSTEM_ICON_BASE, _icon_name + from model.collection import group_by_manufacturer + from sitegen.render import SYSTEM_ICON_BASE, console_icon_name db = load_database(str(ROOT / "database.json")) names = sorted({ - _icon_name(manufacturer, console) - for manufacturer, consoles in _group_by_manufacturer(db).items() + console_icon_name(manufacturer, console) + for manufacturer, consoles in group_by_manufacturer(db).items() for console in consoles }) ICON_DIR.mkdir(parents=True, exist_ok=True) diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 9b6681c18..03715c184 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -85,22 +85,22 @@ from resolve.packfiles import ( from packs.archive import DamagedArchiveError from packs.platformpack import generate_split_packs -from packs.datatrees import _MISSING_DATA_DIRS +from packs.datatrees import MISSING_DATA_DIRS from packs.emulatorpack import generate_emulator_pack, generate_system_pack -from packs.finalize import _baseline_shortfall, verify_and_finalize_packs +from packs.finalize import baseline_shortfall, verify_and_finalize_packs from packs.manifest import generate_install_list, generate_manifest from packs.md5pack import generate_md5_pack from packs.naming import ( - _expected_pack_names, - _narrowings, - _pack_variant, - _platform_pack_stem, - _platform_target, - _system_tag, + expected_pack_names, + pack_narrowings, + pack_variant, + platform_pack_stem, + platform_target, + system_tag, ) from packs.platformpack import generate_pack from packs.scope import pack_systems, platform_list_version -from packs.standalone import STANDALONE_DIR, _standalone_copies +from packs.standalone import STANDALONE_DIR, standalone_copies from packs.targets import generate_target_manifests, target_list @@ -382,7 +382,7 @@ def _run_manifest_mode( target_cores=tc, source=source, regions=getattr(args, "regions", None), - target_name=_platform_target( + target_name=platform_target( representative, args.target, args.platforms_dir ), offline=args.offline, @@ -392,10 +392,10 @@ def _run_manifest_mode( ) narrow_suffix = "".join( tag.lower() - for tag, _label in _narrowings( + for tag, _label in pack_narrowings( source, getattr(args, "regions", None), - _platform_target(representative, args.target, args.platforms_dir), + platform_target(representative, args.target, args.platforms_dir), False, required_only, no_game_data=getattr(args, "no_game_data", False), @@ -438,7 +438,7 @@ def _run_manifest_mode( alias_manifest["detect"] = alias_install.get("detect", []) # Placed and completed as the representative's are: # copied raw, an alias's copies named no source. - alias_manifest["standalone_copies"] = _standalone_copies( + alias_manifest["standalone_copies"] = standalone_copies( alias_install.get("standalone_copies", []), {name: emu_profiles[name] for name in _platform_cores(alias_cfg, emu_profiles)}, @@ -528,7 +528,7 @@ def _run_verify_packs(args: argparse.Namespace) -> None: ) # After an --all-variants build every variant is named, so none of the # six packs the run wrote passes unmentioned. - expected = _expected_pack_names( + expected = expected_pack_names( platforms, args.platforms_dir, check.regions, @@ -564,7 +564,7 @@ def _run_verify_packs(args: argparse.Namespace) -> None: # A group pack and a pack built for the platform alone can both be # present, and each one is a pack of this platform. for pack_name in found: - variant = _pack_variant(pack_name) + variant = pack_variant(pack_name) if variant is None: # One BIOS per slot: the slot choice is not replayed here. print( @@ -593,7 +593,7 @@ def _run_verify_packs(args: argparse.Namespace) -> None: # These explain a baseline short of its total: a dump whose hash # the frontend refuses is left out on purpose, and a file the # collection does not hold cannot be packed (verify reports it). - shortfall = ", ".join(_baseline_shortfall(bl_excluded, bl_absent)) + shortfall = ", ".join(baseline_shortfall(bl_excluded, bl_absent)) excluded = f" ({shortfall})" if shortfall else "" counts = ( f"{bl_present}/{bl_checked} baseline{excluded}, " @@ -722,7 +722,7 @@ def _run_platform_packs( zip_path = None zip_paths: list = [] tc = target_cores_cache.get(representative) if args.target else None - named_target = _platform_target(representative, args.target, args.platforms_dir) + named_target = platform_target(representative, args.target, args.platforms_dir) if _skip_empty_truth(args, source, representative, emu_profiles, tc, failed): continue try: @@ -834,7 +834,7 @@ def _group_pack_name( source, required_only = variant narrow_tags = "".join( tag - for tag, _label in _narrowings( + for tag, _label in pack_narrowings( source, getattr(args, "regions", None), named_target, @@ -843,12 +843,12 @@ def _group_pack_name( no_game_data=getattr(args, "no_game_data", False), ) ) - stem = _platform_pack_stem( + stem = platform_pack_stem( group_platforms, representative, args.platforms_dir ) return ( f"{stem}{narrow_tags}_BIOS_Pack" - f"{_system_tag(system_filter)}.zip" + f"{system_tag(system_filter)}.zip" ) @@ -1033,7 +1033,7 @@ def _given_flags(args: argparse.Namespace) -> set[str]: def main() -> None: # One run's account: tests call main() repeatedly in one process, and a # notice left by an earlier run failed a later one that missed nothing. - _MISSING_DATA_DIRS.clear() + MISSING_DATA_DIRS.clear() with contextlib.ExitStack() as held: try: _main(held) @@ -1042,10 +1042,10 @@ def main() -> None: # report it: the run stops with the file to restore. print(f"ERROR: {exc}", file=sys.stderr) sys.exit(1) - if _MISSING_DATA_DIRS: + if MISSING_DATA_DIRS: print( "ERROR: packs written without data directories that are not cached: " - f"{', '.join(sorted(_MISSING_DATA_DIRS))} (run refresh_data_dirs.py)", + f"{', '.join(sorted(MISSING_DATA_DIRS))} (run refresh_data_dirs.py)", file=sys.stderr, ) sys.exit(1) diff --git a/scripts/generate_readme.py b/scripts/generate_readme.py index f0acf5699..f661ef303 100644 --- a/scripts/generate_readme.py +++ b/scripts/generate_readme.py @@ -17,7 +17,7 @@ import sys sys.path.insert(0, os.path.dirname(__file__)) from model.database import load_database from core.artifacts import repository_output_lock -from sitegen.readme import _write, generate_readme +from sitegen.readme import write_readme, generate_readme def main() -> None: @@ -44,7 +44,7 @@ def main() -> None: with repository_output_lock("README.md"), contextlib.ExitStack() as held: hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) readme = generate_readme(db, args.platforms_dir, args.db) - _write(readme) + write_readme(readme) if __name__ == "__main__": diff --git a/scripts/generate_site.py b/scripts/generate_site.py index 8a0682aeb..5c338c506 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -23,7 +23,7 @@ sys.path.insert(0, os.path.dirname(__file__)) from core.cli import require_directory from core.artifacts import ArtifactLockBusy, artifact_lock -from sitegen.build import _generate +from sitegen.build import generate_site from sitegen.config import STARLIGHT_CONTENT, STARLIGHT_DIR from sitegen.parts import PUBLISHED_PARTS_FILE @@ -79,7 +79,7 @@ def main() -> None: repository_output_lock(str(PUBLISHED_PARTS_FILE)), \ contextlib.ExitStack() as held: hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) - _generate(args) + generate_site(args) except ArtifactLockBusy as exc: print(f"ERROR: {exc}", file=sys.stderr) sys.exit(1) diff --git a/scripts/installer_build/amalgamate.py b/scripts/installer_build/amalgamate.py index c29961d13..0e59ed274 100644 --- a/scripts/installer_build/amalgamate.py +++ b/scripts/installer_build/amalgamate.py @@ -9,10 +9,8 @@ from collections.abc import Iterator from dataclasses import dataclass, field from pathlib import Path -from core.paths import REPO_ROOT -ROOT = REPO_ROOT PACKAGE = "installer" OUTPUT = "install.py" COMMAND = "python scripts/build_installer.py" diff --git a/scripts/installer_build/eventschema.py b/scripts/installer_build/eventschema.py index 8cdeae9e3..b4a02a2f6 100644 --- a/scripts/installer_build/eventschema.py +++ b/scripts/installer_build/eventschema.py @@ -8,12 +8,11 @@ import json from core.paths import REPO_ROOT -ROOT = REPO_ROOT -OUTPUT = ROOT / "schemas" / "install-events.schema.json" +OUTPUT = REPO_ROOT / "schemas" / "install-events.schema.json" -_spec = importlib.util.spec_from_file_location("install", ROOT / "install.py") +_spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py") if _spec is None or _spec.loader is None: - raise ImportError(f"cannot load {ROOT / 'install.py'}") + raise ImportError(f"cannot load {REPO_ROOT / 'install.py'}") _install = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(_install) diff --git a/scripts/installer_build/installerdoc.py b/scripts/installer_build/installerdoc.py index 6856c33f9..ff5109ed4 100644 --- a/scripts/installer_build/installerdoc.py +++ b/scripts/installer_build/installerdoc.py @@ -28,9 +28,8 @@ if TYPE_CHECKING: from install import LocalCopy, Progress, _OsRule -ROOT = REPO_ROOT -PAGE = ROOT / "wiki" / "installer.md" -INSTALLER = ROOT / "install.py" +PAGE = REPO_ROOT / "wiki" / "installer.md" +INSTALLER = REPO_ROOT / "install.py" _spec = importlib.util.spec_from_file_location("install", INSTALLER) if _spec is None or _spec.loader is None: @@ -216,7 +215,7 @@ def line_menu() -> str: import io from unittest import mock - manifest = json.loads((ROOT / "install" / "retroarch.json").read_text(encoding="utf-8")) + manifest = json.loads((REPO_ROOT / "install" / "retroarch.json").read_text(encoding="utf-8")) files = [*manifest["files"], *(manifest.get("case_variants") or [])] folder = Path(MENU_FOLDER) out = io.StringIO() @@ -266,7 +265,7 @@ class _ListHandler(http.server.SimpleHTTPRequestHandler): def __init__(self, request: socket.socket | tuple[bytes, socket.socket], client_address: tuple[str, int], server: socketserver.BaseServer) -> None: - super().__init__(request, client_address, server, directory=str(ROOT)) + super().__init__(request, client_address, server, directory=str(REPO_ROOT)) def do_GET(self) -> None: if not re.fullmatch(r"/install/[a-z0-9_-]+\.json", self.path): @@ -398,8 +397,8 @@ class Sandbox: is printed here.""" def __enter__(self) -> Sandbox: - (ROOT / "tmp").mkdir(exist_ok=True) - self.root = Path(tempfile.mkdtemp(prefix="installer-doc-", dir=ROOT / "tmp")) + (REPO_ROOT / "tmp").mkdir(exist_ok=True) + self.root = Path(tempfile.mkdtemp(prefix="installer-doc-", dir=REPO_ROOT / "tmp")) self.home = self.root / "home" self.card = self.root / "card" config = self.home / ".config" / "retroarch" / "retroarch.cfg" @@ -458,7 +457,7 @@ class Sandbox: "RETROBIOS_BASE_URL": f"http://127.0.0.1:{self.server.server_address[1]}"} done = subprocess.run( [sys.executable, "-s", "-c", CHILD, json.dumps(spec)], - cwd=ROOT, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, + cwd=REPO_ROOT, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, check=False) if done.returncode not in codes: raise SampleFailed(f"install.py {' '.join(args)} exited " @@ -473,7 +472,7 @@ _RUNS: dict[tuple, str] = {} def _stamp(platform: str) -> tuple[int, int]: return (hash(INSTALLER.read_bytes()), - hash((ROOT / "install" / f"{platform}.json").read_bytes())) + hash((REPO_ROOT / "install" / f"{platform}.json").read_bytes())) class _LazySandbox: @@ -529,7 +528,7 @@ def _fenced(lines: list[str]) -> str: def list_date(platform: str) -> str: """The day the committed list was generated, which dates its samples.""" - manifest = json.loads((ROOT / "install" / f"{platform}.json").read_text(encoding="utf-8")) + manifest = json.loads((REPO_ROOT / "install" / f"{platform}.json").read_text(encoding="utf-8")) return manifest["generated"][:10] diff --git a/scripts/installer_build/launcherindex.py b/scripts/installer_build/launcherindex.py index ef6459516..0e1e2a320 100644 --- a/scripts/installer_build/launcherindex.py +++ b/scripts/installer_build/launcherindex.py @@ -13,7 +13,7 @@ from installer_build.port import ( BATOCERA_ZIP, MUOS_APP, TOOLS_ZIP, - _packs_table, + packs_table, archive_members, pinned_installer_sha256, ) @@ -35,7 +35,7 @@ def _entry(field: str, name: str, source: Path | None, root: Path) -> dict: """A member as the list records it: where it comes from, its size and hash, and whether it is executable in the repository.""" if source is None: - data = _packs_table(root) + data = packs_table(root) origin: dict = {"content": data.decode("utf-8")} executable = False else: diff --git a/scripts/installer_build/pins.py b/scripts/installer_build/pins.py index 36079915e..ecce09eb5 100644 --- a/scripts/installer_build/pins.py +++ b/scripts/installer_build/pins.py @@ -10,7 +10,6 @@ from core.paths import REPO_ROOT from model.guides import PS1_NAME, SH_NAME -ROOT = REPO_ROOT INSTALLER = "install.py" # Each bootstrap and its one pin line, the value between the two groups. PINS: dict[str, re.Pattern[str]] = { @@ -25,11 +24,11 @@ PIN: dict[str, re.Pattern[str]] = { COMMAND = "python scripts/pin_installer.py" -def installer_sha256(root: Path = ROOT) -> str: +def installer_sha256(root: Path = REPO_ROOT) -> str: return hashlib.sha256((root / INSTALLER).read_bytes()).hexdigest() -def stale_pins(root: Path = ROOT) -> list[str]: +def stale_pins(root: Path = REPO_ROOT) -> list[str]: """The bootstraps whose pin is not the SHA-256 of install.py.""" digest = installer_sha256(root) stale = [] @@ -42,7 +41,7 @@ def stale_pins(root: Path = ROOT) -> list[str]: return stale -def write_pins(root: Path = ROOT) -> list[str]: +def write_pins(root: Path = REPO_ROOT) -> list[str]: """Rewrite each stale pin. Returns the bootstraps written.""" digest = installer_sha256(root) written = [] diff --git a/scripts/installer_build/port.py b/scripts/installer_build/port.py index 158219da6..43d8ff174 100644 --- a/scripts/installer_build/port.py +++ b/scripts/installer_build/port.py @@ -112,23 +112,23 @@ def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]: from resolve.grouping import group_identical_platforms from model.registry import list_release_pack_platforms from model.platforms import load_platform_config - from packs.naming import _name_part, _platform_pack_stem + from packs.naming import file_name_part, platform_pack_stem platforms_dir = str(root / "platforms") pool = list_release_pack_platforms(platforms_dir) labels: dict[str, str] = {} for group, representative in group_identical_platforms(pool, platforms_dir): - stem = _platform_pack_stem(group, representative, platforms_dir) + stem = platform_pack_stem(group, representative, platforms_dir) config = load_platform_config(representative, platforms_dir) version = config.get("version", config.get("dat_version", "")) - tag = f"_{_name_part(str(version))}" if version else "" + tag = f"_{file_name_part(str(version))}" if version else "" label = stem[: -len(tag)] if tag and stem.endswith(tag) else stem for platform in group: labels[platform] = label return dict(sorted(labels.items())) -def _packs_table(root: Path) -> bytes: +def packs_table(root: Path) -> bytes: return "".join(f"{platform}\t{label}\n" for platform, label in release_pack_labels(root).items()).encode() @@ -144,17 +144,17 @@ def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path: ) # The packs' member writer: imported here, as it loads the whole # pack builder, which a caller reading ARCHIVES does not need. - from packs.archive import _add_pack_member + from packs.archive import add_pack_member members = archive_members(name, root) output.parent.mkdir(parents=True, exist_ok=True) scratch = output.with_name(f".{output.name}.tmp") table = output.with_name(f".{output.name}.{PACKS_TABLE}") - table.write_bytes(_packs_table(root)) + table.write_bytes(packs_table(root)) try: with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: for member, path in members: - _add_pack_member(zf, str(path or table), member) + add_pack_member(zf, str(path or table), member) finally: table.unlink() scratch.replace(output) diff --git a/scripts/installer_build/pypi.py b/scripts/installer_build/pypi.py index 68d5386e9..0f208e414 100644 --- a/scripts/installer_build/pypi.py +++ b/scripts/installer_build/pypi.py @@ -15,9 +15,8 @@ from model.guides import SH_NAME from installer_build.pins import PIN -ROOT = REPO_ROOT -PACKAGE_DIR = ROOT / "packaging" / "pypi" -DEFAULT_OUTPUT = ROOT / "tmp" / "pypi-dist" +PACKAGE_DIR = REPO_ROOT / "packaging" / "pypi" +DEFAULT_OUTPUT = REPO_ROOT / "tmp" / "pypi-dist" MODULE = "retrobios" # The launcher. runpy runs install.py as __main__, so its own __main__ block @@ -51,7 +50,7 @@ def package_version(stamps: list[int]) -> str: def install_py_commits() -> list[int]: """Commit times of install.py, newest first, from git.""" - out = subprocess.run(["git", "log", "--format=%ct", "--", "install.py"], cwd=ROOT, + out = subprocess.run(["git", "log", "--format=%ct", "--", "install.py"], cwd=REPO_ROOT, capture_output=True, text=True, check=True).stdout return [int(line) for line in out.split()] @@ -59,8 +58,8 @@ def install_py_commits() -> list[int]: def installer_bytes() -> bytes: """install.py, refused unless it is the one install.sh pins: the package then runs the installer the one-line command runs, under the same id.""" - data = (ROOT / "install.py").read_bytes() - pins = PIN[SH_NAME].findall((ROOT / "install.sh").read_text(encoding="utf-8")) + data = (REPO_ROOT / "install.py").read_bytes() + pins = PIN[SH_NAME].findall((REPO_ROOT / "install.sh").read_text(encoding="utf-8")) if pins != [hashlib.sha256(data).hexdigest()]: raise ValueError("install.py is not the installer install.sh pins: recompute the pin") return data @@ -72,7 +71,7 @@ def stage(folder: Path, version: str) -> None: module.mkdir(parents=True) for name in ("pyproject.toml", "README.md"): shutil.copyfile(PACKAGE_DIR / name, folder / name) - shutil.copyfile(ROOT / "LICENSE", folder / "LICENSE") + shutil.copyfile(REPO_ROOT / "LICENSE", folder / "LICENSE") shutil.copyfile(PACKAGE_DIR / MODULE / "__main__.py", module / "__main__.py") (module / "__init__.py").write_text(LAUNCHER.format(version=version), encoding="utf-8") (module / "install.py").write_bytes(installer_bytes()) @@ -86,7 +85,7 @@ def build(output_dir: Path) -> tuple[Path, Path]: for pattern in ("*.whl", "*.tar.gz"): for old in output_dir.glob(f"{MODULE}-{pattern}"): old.unlink() - scratch = ROOT / "tmp" + scratch = REPO_ROOT / "tmp" scratch.mkdir(exist_ok=True) with tempfile.TemporaryDirectory(prefix="pypi-stage-", dir=scratch) as name: folder = Path(name) / "retrobios" diff --git a/scripts/make_og_cards.py b/scripts/make_og_cards.py index 9d36b353f..a4b1c1e3e 100644 --- a/scripts/make_og_cards.py +++ b/scripts/make_og_cards.py @@ -73,7 +73,7 @@ def system_cards() -> dict[str, tuple[str, str]]: system pages are written from.""" from model.composition import GAME_DATA_TOPS from model.database import load_database - from model.collection import _group_by_manufacturer, _slug + from model.collection import group_by_manufacturer, manufacturer_slug def lead(manufacturer: str) -> str: # Other holds one folder per emulator, a game publisher's page its @@ -82,9 +82,9 @@ def system_cards() -> dict[str, tuple[str, str]]: return "Game data for" return "Files kept for the emulators" if manufacturer == "Other" else "BIOS files for" - manufacturers = _group_by_manufacturer(load_database(str(ROOT / "database.json"))) + manufacturers = group_by_manufacturer(load_database(str(ROOT / "database.json"))) return { - f"systems/{_slug(manufacturer)}": ( + f"systems/{manufacturer_slug(manufacturer)}": ( manufacturer, consoles_tagline(list(consoles), lead(manufacturer))) for manufacturer, consoles in sorted(manufacturers.items()) } diff --git a/scripts/mame_ref_audit.py b/scripts/mame_ref_audit.py index 8ce0a2217..a42fc9b45 100644 --- a/scripts/mame_ref_audit.py +++ b/scripts/mame_ref_audit.py @@ -29,7 +29,7 @@ sys.path.insert(0, os.path.dirname(__file__)) from core import upstream from core.cli import require_directory from model.safeparse import yaml_load -from scraper.mame_parser import _MACHINE_MACROS, strip_comments +from scraper.mame_parser import MACHINE_MACROS, strip_comments # An optional role word names the repository the lines are in. DRIVER_REF = re.compile(r"^(?:(source|upstream) )?(src/[\w./+-]+):(\d+)$") @@ -50,7 +50,7 @@ class Finding: def declares(line: str, set_name: str) -> bool: """Whether this line is the machine declaration of that set.""" clean = strip_comments(line) - match = _MACHINE_MACROS.search(clean) + match = MACHINE_MACROS.search(clean) if not match: return False args = clean[match.end():].split(",") diff --git a/scripts/model/collection.py b/scripts/model/collection.py index 2fee667a1..0792e044e 100644 --- a/scripts/model/collection.py +++ b/scripts/model/collection.py @@ -16,7 +16,7 @@ from model.composition import GAME_DATA_TOPS from model.profiles import load_emulator_profiles -def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]: +def copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]: """sha1 -> every (manufacturer, console, file name) holding a copy. The database keeps one path per content, deduplication having left one @@ -39,7 +39,7 @@ def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]: return places -def _slug(manufacturer: str) -> str: +def manufacturer_slug(manufacturer: str) -> str: return manufacturer.lower().replace(" ", "-") @@ -65,7 +65,7 @@ def collection_paths(db: dict) -> dict[str, set[str]]: return paths -def _group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]: +def group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]: """Group files by manufacturer -> console -> files. The database keeps one path per content, and a copy filed elsewhere was @@ -76,7 +76,7 @@ def _group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]: """ files = db.get("files", {}) manufacturers: dict[str, dict[str, list]] = {} - for sha1, where in _copy_places(db).items(): + for sha1, where in copy_places(db).items(): for manufacturer, console in sorted({(m, c) for m, c, _ in where}): manufacturers.setdefault(manufacturer, {}).setdefault(console, []).append(files[sha1]) return _engine_sections(manufacturers) @@ -94,7 +94,7 @@ def _engine_sections(manufacturers: dict[str, dict[str, list]]) -> dict[str, dic the engine's name (SECTION_LABELS), its address unchanged. """ - profiles = {key: profile for key, profile in _profiles_on_disk().items() + profiles = {key: profile for key, profile in profiles_on_disk().items() if profile.get("type") != "alias" and profile.get("role") != "test"} engines = _Engines(profiles, _file_readers(profiles)) out: dict[str, dict[str, list]] = {} @@ -168,7 +168,7 @@ def _join_other_folders(out: dict[str, dict[str, list]]) -> None: for folder in sorted(others): top = next((t for t in out if t in GAME_DATA_TOPS and t.casefold() == folder.casefold()), None) - if top is None or top in _PROGRAM_TOPS: + if top is None or top in PROGRAM_TOPS: continue sections = out[top] target = next((c for c in sections if c.casefold() == folder.casefold()), folder) @@ -179,27 +179,27 @@ def _join_other_folders(out: dict[str, dict[str, list]]) -> None: *(f for f in others.pop(folder) if str(f.get("sha1", "")) not in held)] -def _profiles_on_disk() -> dict[str, dict]: - return _profiles_in(str(siteinputs.current().emulators), skip_aliases=False) +def profiles_on_disk() -> dict[str, dict]: + return profiles_in(str(siteinputs.current().emulators), skip_aliases=False) @functools.cache -def _profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]: +def profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]: return load_emulator_profiles(emulators_dir, skip_aliases=skip_aliases) # (manufacturer slug, folder, sha1) -> the (manufacturer slug, console) a # copy's card went to when the system pages file it outside its folder: # ScummVM's engine data under Other/ScummVM, neogeo.zip under Arcade. -_card_moves: dict[tuple[str, str, str], tuple[str, str]] = {} +card_moves: dict[tuple[str, str, str], tuple[str, str]] = {} def record_card_move(manufacturer: str, folder: str, sha1: str, to_manufacturer: str, to_console: str) -> None: """Mark that the card of the copy under bios/// sits in the section (to_manufacturer, to_console).""" - _card_moves[(_slug(manufacturer), folder, str(sha1))] = ( - _slug(to_manufacturer), to_console) + card_moves[(manufacturer_slug(manufacturer), folder, str(sha1))] = ( + manufacturer_slug(to_manufacturer), to_console) # System display names. A system is named by the heading of the console @@ -212,7 +212,7 @@ def record_card_move(manufacturer: str, folder: str, sha1: str, # Folders that file copies by the emulator or board that loads them. Their # headings name a program, not a system. -_PROGRAM_TOPS = frozenset({"Other", "Arcade"}) +PROGRAM_TOPS = frozenset({"Other", "Arcade"}) # A section whose folder is a short name the code reads, headed with the diff --git a/scripts/model/nodedup.py b/scripts/model/nodedup.py index a2555dce7..12a7878c9 100644 --- a/scripts/model/nodedup.py +++ b/scripts/model/nodedup.py @@ -49,6 +49,6 @@ NODEDUP_DIRS = { } -def _in_nodedup_dir(path: str) -> bool: +def in_nodedup_dir(path: str) -> bool: parts = Path(path).parts return any(nodedup in parts for nodedup in NODEDUP_DIRS) diff --git a/scripts/model/profiles.py b/scripts/model/profiles.py index e804daae2..9c8ba0910 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 from core.paths import REPO_ROOT @@ -24,7 +24,7 @@ from core.paths import REPO_ROOT CONTENT_CHECKS = frozenset({"romdir", "masked_sha1"}) -_emulator_profiles_cache: dict[tuple[str, bool], dict[str, dict]] = {} +emulator_profiles_cache: dict[tuple[str, bool], dict[str, dict]] = {} class ProfileSelectionError(ValueError): @@ -40,14 +40,14 @@ def profiles_for_systems( other profile writes atari-2600, and an exact match built two different packs under one file name, the second replacing the first. """ - wanted = {_norm_system_id(sid) for sid in system_ids} + wanted = {norm_system_id(sid) for sid in system_ids} matching = [] for name, profile in sorted(profiles.items()): if profile.get("type") in ("launcher", "alias") or profile.get("role") == "test": continue if standalone and "standalone" not in profile.get("type", "libretro"): continue - if wanted & {_norm_system_id(sid) for sid in profile.get("systems", [])}: + if wanted & {norm_system_id(sid) for sid in profile.get("systems", [])}: matching.append(name) return matching @@ -73,8 +73,8 @@ def entry_serves_systems(entry: dict, profile: dict, system_ids: list[str]) -> b serves every system of its profile, the rule a platform pack applies to core extras. """ - wanted = {_norm_system_id(sid) for sid in system_ids} - return bool(wanted & {_norm_system_id(sid) for sid in entry_system_ids(entry, profile)}) + wanted = {norm_system_id(sid) for sid in system_ids} + return bool(wanted & {norm_system_id(sid) for sid in entry_system_ids(entry, profile)}) def select_emulator_profiles( @@ -187,8 +187,8 @@ def load_emulator_profiles( ) -> dict[str, dict]: """Load all emulator YAML profiles from a directory (cached).""" cache_key = (os.path.realpath(emulators_dir), skip_aliases) - if cache_key in _emulator_profiles_cache: - return _emulator_profiles_cache[cache_key] + if cache_key in emulator_profiles_cache: + return emulator_profiles_cache[cache_key] if skip_aliases: # A filter over the full set: parsed once, 534 YAML files cost 1.6 s # every time a process asked for both variants. @@ -197,7 +197,7 @@ def load_emulator_profiles( for name, profile in load_emulator_profiles(emulators_dir, False).items() if profile.get("type") != "alias" } - _emulator_profiles_cache[cache_key] = profiles + emulator_profiles_cache[cache_key] = profiles return profiles if importlib.util.find_spec("yaml") is None: # Every consumer reads {} as "this repo documents no emulator", which @@ -223,7 +223,7 @@ def load_emulator_profiles( _normalize_hash_fields(profile) derive_member_requirements(profile) profiles[f.stem] = profile - _emulator_profiles_cache[cache_key] = profiles + emulator_profiles_cache[cache_key] = profiles return profiles diff --git a/scripts/model/region.py b/scripts/model/region.py index 23539c6bd..99073075b 100644 --- a/scripts/model/region.py +++ b/scripts/model/region.py @@ -57,11 +57,11 @@ AREA_TERRITORIES: dict[str, frozenset[str]] = { "asia-pal": frozenset({"china"}), } -_PARENT: dict[str, str] = { +PARENT: dict[str, str] = { member: parent for parent, members in REGION_TREE.items() for member in members } -REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(_PARENT)) +REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(PARENT)) # Accepted on the CLI and for legacy profile values. Every territory also # answers to its ISO 3166-1 code: `au` alone was unknown, and the closest @@ -149,8 +149,8 @@ def comparable(a: str, b: str) -> bool: territory it serves.""" return ( a == b - or _PARENT.get(a) == b - or _PARENT.get(b) == a + or PARENT.get(a) == b + or PARENT.get(b) == a or a in AREA_TERRITORIES.get(b, ()) or b in AREA_TERRITORIES.get(a, ()) ) diff --git a/scripts/model/registry.py b/scripts/model/registry.py index d8e3672be..39a06f61a 100644 --- a/scripts/model/registry.py +++ b/scripts/model/registry.py @@ -74,7 +74,7 @@ def list_release_pack_platforms(platforms_dir: str = "platforms") -> list[str]: VERSIONS_FILE = "data/.versions.json" -def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]: +def load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]: path = Path(versions_path) if not path.exists(): return {} diff --git a/scripts/model/romfolders.py b/scripts/model/romfolders.py index 2e29b70d7..b9fb58b59 100644 --- a/scripts/model/romfolders.py +++ b/scripts/model/romfolders.py @@ -6,7 +6,7 @@ the BIOS folder, each folder with the system name the OS gives it, the extensions it lists and the core it starts by default. Those files hold the OS's facts only. Which repository system a folder is, and which profile its core is, is decided here, through the one alias table in model/systems.py -(`SYSTEM_ALIASES`, `_norm_system_id`) and the profiles' `cores:` lists, so a +(`SYSTEM_ALIASES`, `norm_system_id`) and the profiles' `cores:` lists, so a change to either reaches every setup without a rescrape. """ @@ -16,7 +16,7 @@ import re from dataclasses import dataclass, field from pathlib import Path -from model.systems import _norm_system_id +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 from model.platforms import load_platform_config, native_layer @@ -70,7 +70,7 @@ class SystemResolver: The universe is every system a profile or a platform file names. A name resolves, in this order, as one of those ids, as a name a platform's own file gives a system (`native_system`, the folder Batocera calls `psx`), - or through `_norm_system_id`, which applies SYSTEM_ALIASES then drops the + or through `norm_system_id`, which applies SYSTEM_ALIASES then drops the maker prefix and separators. A name nothing matches stays unresolved: a new abbreviation goes into SYSTEM_ALIASES, never into a table here. @@ -89,7 +89,7 @@ class SystemResolver: def __post_init__(self) -> None: for sid in self.ids: - self.by_norm.setdefault(_norm_system_id(sid), set()).add(sid) + self.by_norm.setdefault(norm_system_id(sid), set()).add(sid) for members in self.by_norm.values(): best = min(members, key=lambda s: (-self.profile_use.get(s, 0), -len(s), s)) for sid in members: @@ -123,7 +123,7 @@ class SystemResolver: def equivalents(self, sid: str) -> set[str]: """Every id spelling the same machine as sid, sid included.""" - return set(self.by_norm.get(_norm_system_id(sid), ())) | {sid} + return set(self.by_norm.get(norm_system_id(sid), ())) | {sid} def _answer(self, found: set[str], basis: str) -> Resolution: return Resolution(sorted({self.canonical(s) for s in found}), basis) @@ -139,7 +139,7 @@ class SystemResolver: own = self.native.get(platform, {}).get(lowered) if own and len(own) == 1: return self._answer(own, f"native name of {platform}") - norm = self.by_norm.get(_norm_system_id(lowered)) + norm = self.by_norm.get(norm_system_id(lowered)) if norm: return self._answer(norm, "normalized id") claimed = [ diff --git a/scripts/model/siteinputs.py b/scripts/model/siteinputs.py index 57563d596..d6727bbd2 100644 --- a/scripts/model/siteinputs.py +++ b/scripts/model/siteinputs.py @@ -13,14 +13,12 @@ from pathlib import Path from core.paths import REPO_ROOT -ROOT = REPO_ROOT - @dataclass(frozen=True) class SiteInputs: - db: Path = ROOT / "database.json" - emulators: Path = ROOT / "emulators" - platforms: Path = ROOT / "platforms" + db: Path = REPO_ROOT / "database.json" + emulators: Path = REPO_ROOT / "emulators" + platforms: Path = REPO_ROOT / "platforms" _current = [SiteInputs()] diff --git a/scripts/model/sourceref.py b/scripts/model/sourceref.py index e5a659821..5cb22e2b4 100644 --- a/scripts/model/sourceref.py +++ b/scripts/model/sourceref.py @@ -13,7 +13,7 @@ from typing import Iterable, Iterator _REF_RE = re.compile(r"^(?P[^:]+?)(?::(?P\d+)(?:-(?P\d+))?)?$") _BARE_RANGE_RE = re.compile(r"^:?(\d+(?:-\d+)?)$") _SPLIT_RE = re.compile(r"[,;]") -_ANNOTATION_RE = re.compile(r"\s*\([^)]*\)?") +ANNOTATION_RE = re.compile(r"\s*\([^)]*\)?") _LOCATED_RE = re.compile(r"^[^\s:]+:\d+(?:-\d+)?$") @@ -28,7 +28,7 @@ REPO_ROLES = ("source", "upstream") _BINARY_SUFFIXES = ( ".dll", ".exe", ".so", ".dylib", ".apk", ".elf", ".o", ".a", ".jar", ".dex", ) -_HEX_ADDRESS_RE = re.compile(r"\b0x[0-9a-fA-F]{2,}") +HEX_ADDRESS_RE = re.compile(r"\b0x[0-9a-fA-F]{2,}") def is_binary_citation(path: str) -> bool: @@ -39,7 +39,7 @@ def is_binary_citation(path: str) -> bool: of any repository holds those bytes, so the ref can neither anchor nor break: 77 parts of `future-pinball-fploader` alone were reported GONE. """ - if _HEX_ADDRESS_RE.search(path): + if HEX_ADDRESS_RE.search(path): return True if " " not in path: # A bare `DesktopKinect.dll` names a shipped library, never a source @@ -108,7 +108,7 @@ def split_source_ref(ref: str) -> list[RefPart]: """ parts: list[RefPart] = [] for raw in split_outside_parentheses(str(ref or "")): - chunk = _trim_prose(_ANNOTATION_RE.sub("", raw).strip()) + chunk = trim_prose(ANNOTATION_RE.sub("", raw).strip()) if not chunk: continue bare = _BARE_RANGE_RE.match(chunk) @@ -206,7 +206,7 @@ def split_outside_parentheses(text: str) -> list[str]: return [c for c in (chunk.strip() for chunk in chunks) if c] -def _trim_prose(chunk: str) -> str: +def trim_prose(chunk: str) -> str: """Drop a trailing comment written without parentheses. `libretro.cpp:1520-1521 candidates_a1200` cites a location followed by a @@ -445,7 +445,7 @@ def _run_spans(line: str, match: re.Match) -> tuple[list[tuple[int, int]], int]: return spans, end -def _prose_runs( +def prose_runs( text: str, known: frozenset[str] | set[str] = frozenset() ) -> Iterator[tuple[ int, tuple[int, int], tuple[tuple[int, int], ...], tuple[RefPart, ...], str, int diff --git a/scripts/model/systemnames.py b/scripts/model/systemnames.py index e94a2c1fc..769908eb4 100644 --- a/scripts/model/systemnames.py +++ b/scripts/model/systemnames.py @@ -3,27 +3,27 @@ from __future__ import annotations from model import siteinputs -from model.collection import SECTION_LABELS, _PROGRAM_TOPS, _slug +from model.collection import SECTION_LABELS, PROGRAM_TOPS, manufacturer_slug # (manufacturer slug, console) -> the id of the console's heading. Two # folders spelled alike (Sega's "Mega CD" and "Mega-CD") share a slug, and # the second heading took "mega-cd_1" while every link said "mega-cd". -_console_anchors: dict[tuple[str, str], str] = {} +console_anchors: dict[tuple[str, str], str] = {} -_boards_built = [False] +boards_built = [False] # Every (manufacturer, console) section the system pages carry. -_section_pairs: set[tuple[str, str]] = set() +section_pairs: set[tuple[str, str]] = set() # Normalized id -> the console sections spelled that way. _console_sections: dict[str, set[tuple[str, str]]] = {} # A console section by the name its heading reads (Bandai WonderSwan). -_sections_by_name: dict[str, set[tuple[str, str]]] = {} +sections_by_name: dict[str, set[tuple[str, str]]] = {} # Emulator and engine names. A heading spelled like one (Game Engines > # Solarus, ZC > ZC210) files that program's copies and names no system. -_program_names: set[str] = set() +known_program_names: set[str] = set() def program_names(profiles: dict[str, dict]) -> set[str]: @@ -48,7 +48,7 @@ def set_console_sections( group them, or is a set of (manufacturer, console) pairs. ``programs`` are the emulator names, which never name a system. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id pairs = ( {(mfr, console) for mfr, consoles in sections.items() for console in consoles} @@ -59,40 +59,40 @@ def set_console_sections( # system pages file them under Acorn (sitegen.systempages.arcade_board_sections). makers = {mfr for mfr, _console in pairs} pairs |= {parent for parent in SYSTEM_PARENTS.values() - if parent[0] in makers and parent[0] not in _PROGRAM_TOPS} - from core.anchors import _unique, toc_slug + if parent[0] in makers and parent[0] not in PROGRAM_TOPS} + from core.anchors import unique_anchor, toc_slug _console_sections.clear() - _sections_by_name.clear() - _console_anchors.clear() - _section_pairs.clear() - _section_pairs.update(pairs) + sections_by_name.clear() + console_anchors.clear() + section_pairs.clear() + section_pairs.update(pairs) by_maker: dict[str, list[str]] = {} for mfr, console in pairs: by_maker.setdefault(mfr, []).append(console) - for name in {_heading_name(mfr, console).casefold(), console.casefold()}: - _sections_by_name.setdefault(name, set()).add((mfr, console)) + for name in {heading_name(mfr, console).casefold(), console.casefold()}: + sections_by_name.setdefault(name, set()).add((mfr, console)) # In the order the page lists them, after the page title's own id. for mfr, consoles in by_maker.items(): used = {toc_slug(mfr)} for console in sorted(consoles): - _console_anchors[(_slug(mfr), console)] = _unique(toc_slug(console), used) + console_anchors[(manufacturer_slug(mfr), console)] = unique_anchor(toc_slug(console), used) for mfr, console in pairs: spelled = console.lower().replace(" ", "-") slug = mfr.lower().replace(" ", "-") - for key in {_norm_system_id(f"{slug}-{spelled}"), _norm_system_id(spelled)}: + for key in {norm_system_id(f"{slug}-{spelled}"), norm_system_id(spelled)}: _console_sections.setdefault(key, set()).add((mfr, console)) - _program_names.clear() - _program_names.update(name.casefold() for name in programs) + known_program_names.clear() + known_program_names.update(name.casefold() for name in programs) _sections_installed[0] = True # Which ids are boards depends on which have a section elsewhere. - _boards_built[0] = False + boards_built[0] = False _sections_installed = [False] -def _ensure_console_sections() -> None: +def ensure_console_sections() -> None: """Read the sections from the repository when no generator installed them, so a page rendered on its own names systems as the site does.""" if _sections_installed[0]: @@ -100,26 +100,26 @@ def _ensure_console_sections() -> None: import json from model.profiles import load_emulator_profiles - from model.collection import _group_by_manufacturer + from model.collection import group_by_manufacturer inputs = siteinputs.current() with open(inputs.db, encoding="utf-8") as handle: db = json.load(handle) profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False) - set_console_sections(_group_by_manufacturer(db), program_names(profiles)) + set_console_sections(group_by_manufacturer(db), program_names(profiles)) -def _own_section(sys_id: str) -> tuple[str, str] | None: +def own_section(sys_id: str) -> tuple[str, str] | None: """The console section that is this id's own, or None. Of two sections spelled alike (Atari and Camputers both file a Lynx), the one under the maker the id names is kept. Two left is no answer, and neither is a section that files a program's copies. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id - _ensure_console_sections() - places = _console_sections.get(_norm_system_id(sys_id), set()) + ensure_console_sections() + places = _console_sections.get(norm_system_id(sys_id), set()) if len(places) > 1: places = { (mfr, console) for mfr, console in places @@ -131,15 +131,15 @@ def _own_section(sys_id: str) -> tuple[str, str] | None: # A folder under a program's top, named like its own page (Dinothawr) or # like an emulator holds a program's files, not a system's. if ( - mfr in _PROGRAM_TOPS + mfr in PROGRAM_TOPS or console.casefold() == mfr.casefold() - or _heading_name(mfr, console).casefold() in _program_names + or heading_name(mfr, console).casefold() in known_program_names ): return None return mfr, console -def _heading_name(mfr: str, console: str) -> str: +def heading_name(mfr: str, console: str) -> str: """A console heading read out of its page: the maker in front, unless the heading already starts with it or the page is a game publisher's.""" from model.composition import GAME_DATA_TOPS @@ -154,9 +154,9 @@ def _heading_name(mfr: str, console: str) -> str: def system_name(sys_id: str) -> str: """The display name of a system id, the only one a page prints.""" sys_id = str(sys_id) - section = _own_section(sys_id) + section = own_section(sys_id) if section is not None: - return _heading_name(*section) + return heading_name(*section) name = SYSTEM_NAMES.get(sys_id) if name is None: raise KeyError( diff --git a/scripts/model/systems.py b/scripts/model/systems.py index 8c27a8b54..00876f29a 100644 --- a/scripts/model/systems.py +++ b/scripts/model/systems.py @@ -204,7 +204,7 @@ SYSTEM_ALIASES: dict[str, str] = { @functools.cache -def _norm_system_id(sid: str) -> str: +def norm_system_id(sid: str) -> str: """Normalize system ID for cross-platform matching. Resolves known aliases, then strips manufacturer prefixes and separators @@ -259,10 +259,10 @@ def platform_system_names(config: dict, systems: list[str]) -> dict[str, list[st def select_systems(systems: dict, wanted: list[str]) -> dict: """The systems a --system list keeps, by id or normalized id.""" - norm = {_norm_system_id(s) for s in wanted} + norm = {norm_system_id(s) for s in wanted} return { sid: data for sid, data in systems.items() - if sid in wanted or _norm_system_id(sid) in norm + if sid in wanted or norm_system_id(sid) in norm } @@ -295,7 +295,7 @@ def resolve_system_arg( by_key[_name_key(alias)] = [sid] by_norm: dict[str, list[str]] = {} for sid in systems: - by_norm.setdefault(_norm_system_id(sid), []).append(sid) + by_norm.setdefault(norm_system_id(sid), []).append(sid) value = value.strip() tokens = [value] if value.lower() in exact else value.split(",") @@ -308,7 +308,7 @@ def resolve_system_arg( found = ( exact.get(token.lower()) or (keyed if len(keyed) == 1 else None) - or by_norm.get(_norm_system_id(token)) + or by_norm.get(norm_system_id(token)) ) if not found: unknown.append(token) @@ -335,6 +335,6 @@ def system_index(profiles: dict) -> dict[str, tuple[str, set[str]]]: if p.get("type") in ("alias", "launcher") or p.get("role") == "test": continue for sys_id in p.get("systems", []): - key = _norm_system_id(sys_id) + key = norm_system_id(sys_id) index.setdefault(key, (sys_id, set()))[1].add(name) return index diff --git a/scripts/packs/archive.py b/scripts/packs/archive.py index 0204deb7e..5e39a8ca9 100644 --- a/scripts/packs/archive.py +++ b/scripts/packs/archive.py @@ -12,10 +12,10 @@ from dataclasses import dataclass, field from pathlib import Path from core.artifacts import set_plain_mode -from core.deterministic_zip import _FIXED_DATE_TIME +from core.deterministic_zip import FIXED_DATE_TIME from core.hashing import compute_hashes from core.paths import sanitize_pack_path -from packs.paths import _has_path_conflict, _register_path, placement_block +from packs.paths import has_path_conflict, register_path, placement_block # Formats that are already compressed: deflating them again took 28 s of the @@ -54,7 +54,7 @@ class PackRecord: self.sources: dict[str, str] = {} -def _add_pack_member( +def add_pack_member( zf: zipfile.ZipFile | PackRecord, source_path: str, arcname: str ) -> None: """Add a file to the pack with metadata that does not depend on the build. @@ -71,7 +71,7 @@ def _add_pack_member( zf.members.append(arcname) zf.sources[arcname] = source_path return - info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME) + info = zipfile.ZipInfo(filename=arcname, date_time=FIXED_DATE_TIME) info.compress_type = _member_compression(arcname) # The executable bit is the one permission worth carrying: the RetroDECK # pack ships the two Voxatron engine binaries, and a user who extracts @@ -89,7 +89,7 @@ def _add_pack_member( shutil.copyfileobj(source, target, 1024 * 1024) -def _write_generated_member( +def write_generated_member( zf: zipfile.ZipFile | PackRecord, arcname: str, text: str ) -> None: """Write a pack member the builder composes rather than copies. @@ -102,14 +102,14 @@ def _write_generated_member( if isinstance(zf, PackRecord): zf.members.append(arcname) return - info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME) + info = zipfile.ZipInfo(filename=arcname, date_time=FIXED_DATE_TIME) info.compress_type = zipfile.ZIP_DEFLATED info.external_attr = 0o100644 << 16 zf.writestr(info, text) @contextlib.contextmanager -def _writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]: +def writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]: """A pack written beside its final name, swapped in once complete. Opened on the final name, a rebuild truncated the previous pack at once, @@ -137,7 +137,7 @@ PACK_DOCUMENTS = ("README.txt", "manifest.json") @dataclass -class _Placed: +class Placed: """The destinations a build has taken, and the folders they open. ``fold`` is whether a case twin of a taken path counts as taken. @@ -150,7 +150,7 @@ class _Placed: def take(self, dest: str) -> None: self.destinations.add(dest) - _register_path(dest, self.destinations, self.parents) + register_path(dest, self.destinations, self.parents) if self.fold: self.lower.add(dest.lower()) @@ -158,13 +158,13 @@ class _Placed: return dest in self.destinations or (self.fold and dest.lower() in self.lower) def conflicts(self, dest: str) -> bool: - return _has_path_conflict(dest, self.destinations, self.parents) + return has_path_conflict(dest, self.destinations, self.parents) def block(self, dest: str) -> str | None: return placement_block(dest, self.destinations, self.lower, self.parents, self.fold) -def _extract_zip_to_archive( +def extract_zip_to_archive( source_zip: str, dest_prefix: str, target_zf: zipfile.ZipFile | PackRecord, @@ -188,14 +188,14 @@ def _extract_zip_to_archive( data = src.read(info.filename) target_path = f"{dest_prefix}/{clean_name}" if dest_prefix else clean_name member = zipfile.ZipInfo( - filename=target_path, date_time=_FIXED_DATE_TIME + filename=target_path, date_time=FIXED_DATE_TIME ) member.compress_type = _member_compression(target_path) member.external_attr = 0o100644 << 16 target_zf.writestr(member, data) -def _add_zip_to_pack( +def add_zip_to_pack( source_zip: str, dest_path: str, target_zf: zipfile.ZipFile | PackRecord, @@ -214,7 +214,7 @@ def _add_zip_to_pack( target_zf.sources[dest_path] = source_zip return _check_zip_members(source_zip) - _add_pack_member(target_zf, source_zip, dest_path) + add_pack_member(target_zf, source_zip, dest_path) def _check_zip_members(source_zip: str) -> None: @@ -241,7 +241,7 @@ class DamagedArchiveError(OSError): """An archive of the collection whose members fail their own CRC.""" -def _same_bytes(path: str, other: str | None) -> bool: +def same_bytes(path: str, other: str | None) -> bool: if not other: return False if os.path.realpath(path) == os.path.realpath(other): diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py index 543bbc089..cdc50f607 100644 --- a/scripts/packs/coverage.py +++ b/scripts/packs/coverage.py @@ -21,9 +21,9 @@ from packs.verdicts import ( RELEASE_ASSET_PENDING, Severity, Status, - _SEVERITY_ORDER, - _STATUS_ORDER, - _storage_verdict, + SEVERITY_ORDER, + STATUS_ORDER, + storage_verdict, compute_severity, verify_entry_existence, verify_entry_md5, @@ -34,7 +34,7 @@ from resolve.cores import platform_scope_systems, resolve_platform_cores from resolve.launchers import launcher_unproven from resolve.nativemode import digest_algorithm, normalize as normalize_mode, reads_file_contents from resolve.validation import ( - _build_validation_index, + build_validation_index, agnostic_substitute, baseline_verdict, build_ground_truth, @@ -158,7 +158,7 @@ def _builder_placement( path -> copy or None for each slot kept, a user_provided or external one included). """ - from packs.paths import _has_path_conflict, _register_path + from packs.paths import has_path_conflict, register_path shipped: dict[str, str] = {} occupied: dict[str, str | None] = {} @@ -172,10 +172,10 @@ def _builder_placement( if ( full in occupied or (case_insensitive and full.lower() in folded) - or _has_path_conflict(full, seen, parents) + or has_path_conflict(full, seen, parents) ): continue - _register_path(full, seen, parents) + register_path(full, seen, parents) folded.add(full.lower()) occupied[full] = local if local is not None: @@ -414,7 +414,7 @@ class _PlatformTally: """The declaration's result, and the local copy the pack writes for it.""" config = self.run.config mode = self.run.mode - stored = _storage_verdict(file_entry, emulator_pack=False) + stored = storage_verdict(file_entry, emulator_pack=False) if resolve_status == RELEASE_ASSET_PENDING: # Counted as an online build counts it, which fetches the # asset. Under --offline the builder cannot, and neither @@ -496,11 +496,11 @@ class _PlatformTally: return del self.file_status[dest], self.file_severity[dest] prev = None - if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(prev, 0): + if prev is None or STATUS_ORDER.get(cur, 0) > STATUS_ORDER.get(prev, 0): self.file_status[dest] = cur self.file_required[dest] = required prev_sev = self.file_severity.get(dest) - if prev_sev is None or _SEVERITY_ORDER.get(sev, 0) > _SEVERITY_ORDER.get( + if prev_sev is None or SEVERITY_ORDER.get(sev, 0) > SEVERITY_ORDER.get( prev_sev, 0 ): self.file_severity[dest] = sev @@ -819,7 +819,7 @@ def verify_platform( for f in profile.get("files", []) if f.get("hle_fallback") } - validation_index = _build_validation_index(platform_profiles) + validation_index = build_validation_index(platform_profiles) validation_owners = destination_owners(platform_profiles) verify_systems = platform_scope_systems(config, profiles, target_cores, system_filter) @@ -906,11 +906,11 @@ def verify_platform( # (base_destination stripped, as the builder flattens it). The pipeline # compares this set with the archive: equal counts can hide one file # credited here and another written there. - from packs.paths import _flat + from packs.paths import flat_arcname pack_destinations = sorted( - {_flat(dest, base_dest, True) for dest in shipped} | { - _flat(dest, base_dest, True) for dest in placed + {flat_arcname(dest, base_dest, True) for dest in shipped} | { + flat_arcname(dest, base_dest, True) for dest in placed } ) diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index 5f95ed792..7cdea296b 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -20,15 +20,15 @@ from model.database import get_mame_clone_map from model.declarations import OUTER_ROOTS from model.platforms import load_platform_config from model.registry import list_registered_platforms, load_data_dir_registry -from model.systems import _norm_system_id -from packs.gaps import _gap_destination +from model.systems import norm_system_id +from packs.gaps import gap_destination from resolve.archives import archive_entry from resolve.content import content_fits, name_match_size_ok from resolve.directories import directory_members, expand_directory_entries from resolve.launchers import ( LauncherLayer, - _directories as launcher_directories, - _names as launcher_names, + record_directories as launcher_directories, + record_names as launcher_names, bound_launchers, catalogued_model_files, held_record, @@ -39,7 +39,7 @@ from resolve.launchers import ( ) from resolve.layout import system_dir_path from resolve.localfile import resolve_local_file -from resolve.ownership import _foreign_tree, _owner_tokens +from resolve.ownership import foreign_tree, owner_tokens from resolve.standalone import platform_layouts from resolve.validation import ( case_folded_slots, @@ -80,11 +80,11 @@ def load_platform_files( for fe in system.get("files", []): name = fe.get("name", "") if name: - declared.setdefault(_norm_system_id(sys_id), set()).add(name) + declared.setdefault(norm_system_id(sys_id), set()).add(name) for dd in system.get("data_directories", []): ref = dd.get("ref", "") if ref: - platform_data_dirs.setdefault(_norm_system_id(sys_id), set()).add(ref) + platform_data_dirs.setdefault(norm_system_id(sys_id), set()).add(ref) return declared, platform_data_dirs @@ -130,7 +130,7 @@ def folded_declared_slots( return frozenset(slots) -def _build_supplemental_index( +def build_supplemental_index( data_root: str = "data", bios_root: str = "bios" ) -> set[str]: """Build a set of filenames and directory names in data/ and inside bios/ ZIPs. @@ -214,7 +214,7 @@ def _resolve_source( refuse it. """ declared = _declared_content(file_entry or {}) - owners = _owner_tokens(file_entry or {}) + owners = owner_tokens(file_entry or {}) def _can_be(sha1s: list | str) -> bool: if not file_entry or db_files is None: @@ -237,7 +237,7 @@ def _resolve_source( return _can_be([ sha1 for sha1 in by_name.get(name) or [] if db_files is None - or not _foreign_tree(db_files.get(sha1, {}).get("path", ""), owners) + or not foreign_tree(db_files.get(sha1, {}).get("path", ""), owners) ]) # bios/ via database.json by_name @@ -660,7 +660,7 @@ def _resolve_archive_source( return result if result is not None else "missing" -def _first_hash(entry: dict) -> str: +def first_hash(entry: dict) -> str: """The first hash an entry declares, strongest first, or ''.""" for field in ("sha1", "sha256", "md5", "crc32"): value = entry.get(field) @@ -761,7 +761,7 @@ class _ProfileComparison: # takes it: Batocera's standalone Cemu reads keys.txt at # standalone_path, and the libretro Cemu/keys.txt reported here # settled the declaration on a slot the platform never fills. - effective_path = _gap_destination(f, fname, is_standalone, save_root) + effective_path = gap_destination(f, fname, is_standalone, save_root) slot = slot_key(f, is_standalone) seen_key = slot if len(self.layouts) > 1: @@ -907,7 +907,7 @@ class _ProfileComparison: "in_repo": in_repo, "source": source, # What tells this file from a homonym another emulator wants. - "identity": _first_hash(f), + "identity": first_hash(f), } if save_root: entry["root"] = "save" @@ -1011,7 +1011,7 @@ def _cross_reference_profile( else: platform_names = set() for sys_id in systems: - platform_names.update(declared.get(_norm_system_id(sys_id), set())) + platform_names.update(declared.get(norm_system_id(sys_id), set())) # The build a platform runs decides which entries it reads, as in # find_undeclared_files: without a platform, the libretro build. @@ -1108,7 +1108,7 @@ PLATFORM_OWN_FOLDERS = frozenset({""}) def launcher_file_names(record: dict) -> list[str]: """The concrete file names a launcher record reads, in code order. - The names are read as the launcher layer reads them (`launchers._names`): + The names are read as the launcher layer reads them (`launchers.record_names`): a label after the name is dropped ("neocd_z.rom (CDZ)"), and a name with `<` or without an extension is not a file name (a folder the record links, an option value such as hatari2014's "default"). A name with a diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py index aa866c1b7..1d2a33c90 100644 --- a/scripts/packs/datadirs.py +++ b/scripts/packs/datadirs.py @@ -24,7 +24,7 @@ from core.artifacts import file_lock as _file_lock, set_plain_mode from core.cli import InputMissing from core.github import github_token from model.safeparse import yaml_load -from model.registry import VERSIONS_FILE, _load_versions +from model.registry import VERSIONS_FILE, load_versions log = logging.getLogger(__name__) @@ -155,7 +155,7 @@ def _record_version(key: str, record: dict, versions_path: str) -> None: """Set one key under the file lock, so two writers keep both updates.""" path = Path(versions_path) with _file_lock(path.with_name(f".{path.name}.lock")): - versions = _load_versions(versions_path) + versions = load_versions(versions_path) versions[key] = record _save_versions(versions, versions_path) @@ -437,7 +437,7 @@ def _record_archive_size(key: str, entry: dict, versions_path: str) -> None: """ path = Path(versions_path) with _file_lock(path.with_name(f".{path.name}.lock")): - versions = _load_versions(versions_path) + versions = load_versions(versions_path) record = versions.get(key) if record is None or "archive_size" in record: return @@ -446,7 +446,7 @@ def _record_archive_size(key: str, entry: dict, versions_path: str) -> None: if size is None: return with _file_lock(path.with_name(f".{path.name}.lock")): - versions = _load_versions(versions_path) + versions = load_versions(versions_path) if key in versions and "archive_size" not in versions[key]: versions[key]["archive_size"] = size _save_versions(versions, versions_path) @@ -513,7 +513,7 @@ def _decide( """(whether the tree needs a refresh, the remote tag read, the recorded tag). None when the remote could not be read.""" version = entry.get("version", "master") - cached = _load_versions(versions_path).get(key, {}) + cached = load_versions(versions_path).get(key, {}) cached_tag = cached.get("sha") or cached.get("etag") if force or not Path(entry["local_cache"]).exists(): return True, None, cached_tag diff --git a/scripts/packs/datatrees.py b/scripts/packs/datatrees.py index 8d84631ef..3771ec054 100644 --- a/scripts/packs/datatrees.py +++ b/scripts/packs/datatrees.py @@ -13,11 +13,11 @@ from core.hashing import compute_hashes from core.options import reject_unknown from model.declarations import declared_root from model.profiles import entry_system_ids, installed_data_refs -from model.systems import _norm_system_id -from packs.archive import PackRecord, _add_pack_member +from model.systems import norm_system_id +from packs.archive import PackRecord, add_pack_member from packs.datadirs import cache_lock from packs.extras import prefixed_destination -from packs.paths import MEDIA_MARKER, _has_path_conflict, _register_path, lands_on_android +from packs.paths import MEDIA_MARKER, has_path_conflict, register_path, lands_on_android from resolve.cores import resolve_platform_cores as _platform_cores from resolve.layout import core_system_dirs from resolve.standalone import platform_layouts, standalone_set @@ -113,7 +113,7 @@ def core_data_trees( return trees -def _in_data_cache(path: str, data_registry: dict | None) -> bool: +def in_data_cache(path: str, data_registry: dict | None) -> bool: """Whether a resolved file lies in one of the data directory caches.""" real = os.path.realpath(path) return any( @@ -136,7 +136,7 @@ def _tree_references( class _TreeWalkOptions(TypedDict, total=False): - """The keyword options of _data_directory_members.""" + """The keyword options of data_directory_members.""" refs_out: dict | None required_only: bool @@ -160,7 +160,7 @@ def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> s print( f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)" ) - _MISSING_DATA_DIRS.add(ref_key) + MISSING_DATA_DIRS.add(ref_key) return None return local_path @@ -174,7 +174,7 @@ def _tree_files(local_path: str, dd_prefix: str) -> Iterator[tuple[str, str]]: yield src, f"{dd_prefix}/{rel}" if dd_prefix else rel -def _data_directory_members( +def data_directory_members( pack_systems: dict, data_registry: dict | None, platform_name: str, @@ -205,7 +205,7 @@ def _data_directory_members( ``required_only`` leaves out a tree declared ``required: false``, one the core runs without, as it leaves out such a file. """ - reject_unknown("_data_directory_members", options, _TreeWalkOptions.__optional_keys__) + reject_unknown("data_directory_members", options, _TreeWalkOptions.__optional_keys__) refs_out = options.get("refs_out") reclaim = options.get("reclaim") required_only = options.get("required_only", False) @@ -231,11 +231,11 @@ def _data_directory_members( del reclaim[full] elif full in seen_destinations or ( full.lower() in seen_lower and case_insensitive - ) or _has_path_conflict(full, seen_destinations, seen_parents): + ) or has_path_conflict(full, seen_destinations, seen_parents): continue else: seen_destinations.add(full) - _register_path(full, seen_destinations, seen_parents) + register_path(full, seen_destinations, seen_parents) if case_insensitive: seen_lower.add(full.lower()) if refs_out is not None: @@ -243,7 +243,7 @@ def _data_directory_members( yield src, full -def _pack_data_tree( +def pack_data_tree( zf: zipfile.ZipFile | PackRecord, local_cache: str, dd_dest: str, @@ -266,14 +266,14 @@ def _pack_data_tree( src = os.path.join(root, fname) rel = os.path.relpath(src, local_cache) full = f"{dd_dest}/{rel}" if dd_dest else rel - if full.lower() in seen_lower or _has_path_conflict( + if full.lower() in seen_lower or has_path_conflict( full, seen_destinations, seen_parents ): continue seen_destinations.add(full) - _register_path(full, seen_destinations, seen_parents) + register_path(full, seen_destinations, seen_parents) seen_lower.add(full.lower()) - _add_pack_member(zf, src, full) + add_pack_member(zf, src, full) if packed_at is not None: packed_at[full.lower()] = src added += 1 @@ -283,7 +283,7 @@ def _pack_data_tree( # Data directories a pack needed and the cache did not hold. The pack is # written without them, so the run cannot exit as if it were complete: a # refresh refused by a quota left the PPSSPP pack with 2 files, exit 0. -_MISSING_DATA_DIRS: set[str] = set() +MISSING_DATA_DIRS: set[str] = set() def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, list[str]]: @@ -341,7 +341,7 @@ def _tree_group( return group -def _manifest_data_directories( +def manifest_data_directories( members: list[tuple[str, str]], refs: dict[str, tuple[str, tuple[str, ...], str, bool]], registry: dict, @@ -373,11 +373,11 @@ def _manifest_data_directories( versions: dict[str, dict[str, dict]] = {} by_norm: dict[str, list[str]] = {} for sys_id in sorted(platform_systems or ()): - by_norm.setdefault(_norm_system_id(sys_id), []).append(sys_id) + by_norm.setdefault(norm_system_id(sys_id), []).append(sys_id) for src, full in members: ref, systems, prefix, needed = refs[full] if platform_systems is not None: - systems = tuple(own for sid in systems for own in by_norm.get(_norm_system_id(sid), ())) + systems = tuple(own for sid in systems for own in by_norm.get(norm_system_id(sid), ())) key = (ref, prefix) group = grouped.get(key) if group is None: diff --git a/scripts/packs/emulatorcheck.py b/scripts/packs/emulatorcheck.py index 1bef56f5a..f881e3b9a 100644 --- a/scripts/packs/emulatorcheck.py +++ b/scripts/packs/emulatorcheck.py @@ -26,15 +26,15 @@ from packs.verdicts import ( RELEASE_ASSET_PENDING, Severity, Status, - _SEVERITY_ORDER, - _STATUS_ORDER, - _emulator_severity, - _storage_verdict, + SEVERITY_ORDER, + STATUS_ORDER, + emulator_severity, + storage_verdict, ) from resolve.archives import archive_entry, archive_is_optional from resolve.directories import expand_directory_entries from resolve.validation import ( - _build_validation_index, + build_validation_index, build_ground_truth, deliverable, validated_choice, @@ -111,7 +111,7 @@ def _emulator_files( ) -> list[dict]: """The entries of a profile the emulator pack carries.""" from packs.extras import expand_agnostic_entries - from packs.paths import _resolve_destination + from packs.paths import resolve_destination files = expand_agnostic_entries( expand_directory_entries( @@ -142,7 +142,7 @@ def _emulator_files( fe for fe in files if fe.get("archive") - or _resolve_destination(fe, standalone) not in region_drops + or resolve_destination(fe, standalone) not in region_drops ] return files @@ -251,12 +251,12 @@ class _EmulatorPack: ) def occupy(self, dest: str, path: str | None, owner: str) -> None: - from packs.paths import _register_path + from packs.paths import register_path if self.block(dest): return self.placed[dest.lower()] = (path, owner, dest) - _register_path(dest, self.placed_files, self.placed_parents) + register_path(dest, self.placed_files, self.placed_parents) def occupy_trees(self, emu_name: str, profile: dict) -> None: """The profile's data trees follow its files in the pack, which @@ -331,7 +331,7 @@ class _EmulatorPack: self, emu_name: str, profile: dict, files: list[dict], spares: set[str], ) -> list[PlacedResult]: # Verify archives as units (e.g., neogeo.zip, aes.zip) - from packs.paths import _archive_destination + from packs.paths import archive_destination from resolve.packfiles import resolve_file placed_results: list[PlacedResult] = [] @@ -344,7 +344,7 @@ class _EmulatorPack: own_entry = archive_entry(archive, files) # Where the pack puts it: an archive_prefix or pack_structure # moves it, and a loose same-named entry is another file. - dest = _archive_destination( + dest = archive_destination( archive, profile.get("archive_prefix", ""), profile.get("pack_structure"), self.standalone, ) @@ -387,7 +387,7 @@ class _EmulatorPack: def _loose_results( self, emu_name: str, files: list[dict], ) -> dict[str, list[tuple[dict, bool, bool, dict]]]: - from packs.paths import _resolve_destination + from packs.paths import resolve_destination from resolve.packfiles import resolve_file # Results of this emulator, by destination. Several entries of one @@ -426,7 +426,7 @@ class _EmulatorPack: result["ground_truth"] = build_ground_truth(name, self.validation_index) # The slot the emulator pack places this entry in: standalone_path # under --standalone, the sanitised path. - dest = _resolve_destination(file_entry, self.standalone) or name + dest = resolve_destination(file_entry, self.standalone) or name emu_results.setdefault(dest, []).append((result, required, hle, file_entry)) return emu_results @@ -435,7 +435,7 @@ class _EmulatorPack: resolve_status: str, emu_name: str, ) -> dict: """The verdict on a loose profile entry, from its resolution.""" - stored = _storage_verdict(file_entry, emulator_pack=True) + stored = storage_verdict(file_entry, emulator_pack=True) if stored is not None: return stored if resolve_status == RELEASE_ASSET_PENDING: @@ -589,15 +589,15 @@ class _EmulatorPack: self.dest_to_name[dest] = result["name"] cur = result["status"] prev = self.file_status.get(dest) - if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get( + if prev is None or STATUS_ORDER.get(cur, 0) > STATUS_ORDER.get( prev, 0 ): self.file_status[dest] = cur - sev = _emulator_severity(cur, required, hle) + sev = emulator_severity(cur, required, hle) prev_sev = self.file_severity.get(dest) - if prev_sev is None or _SEVERITY_ORDER.get( + if prev_sev is None or SEVERITY_ORDER.get( sev, 0 - ) > _SEVERITY_ORDER.get(prev_sev, 0): + ) > SEVERITY_ORDER.get(prev_sev, 0): self.file_severity[dest] = sev @@ -632,7 +632,7 @@ def verify_emulator( file or tree marked ``required: false`` is left out, and an archive when it and every member it carries are optional, as the builder leaves them. """ - from packs.paths import _resolve_destination + from packs.paths import resolve_destination # Also load aliases for redirect messages all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) @@ -649,7 +649,7 @@ def verify_emulator( # Build validation index from selected profiles only selected_profiles = dict(selected) - validation_index = _build_validation_index(selected_profiles) + validation_index = build_validation_index(selected_profiles) data_registry = load_data_dir_registry(platforms_dir) pack = _EmulatorPack( @@ -681,7 +681,7 @@ def verify_emulator( ) files = [ fe for fe in files - if fe.get("archive") or _resolve_destination(fe, standalone) not in spares + if fe.get("archive") or resolve_destination(fe, standalone) not in spares ] pack.verify_profile(emu_name, profile, files, spares) diff --git a/scripts/packs/emulatorpack.py b/scripts/packs/emulatorpack.py index 532e6d418..db06f3f92 100644 --- a/scripts/packs/emulatorpack.py +++ b/scripts/packs/emulatorpack.py @@ -29,23 +29,23 @@ from model.registry import load_data_dir_registry from model.systems import MANUFACTURER_PREFIXES, system_index from packs.archive import ( PackRecord, - _Placed, - _add_pack_member, - _add_zip_to_pack, - _same_bytes, - _write_generated_member, - _writing_pack, + Placed, + add_pack_member, + add_zip_to_pack, + same_bytes, + write_generated_member, + writing_pack, ) -from packs.datatrees import _MISSING_DATA_DIRS, _pack_data_tree +from packs.datatrees import MISSING_DATA_DIRS, pack_data_tree from packs.extras import emulator_region_drops, emulator_required_spares, expand_agnostic_entries -from packs.naming import _bounded_join, _bounded_pack_name, _name_part, _narrowings -from packs.paths import _archive_destination, _resolve_destination +from packs.naming import bounded_join, bounded_pack_name, file_name_part, pack_narrowings +from packs.paths import archive_destination, resolve_destination from resolve import packfiles as packresolve from resolve.archives import archive_entry, archive_is_optional from resolve.directories import expand_directory_entries from resolve.packfiles import download_external, resolve_file from resolve.validation import ( - _build_validation_index, + build_validation_index, deliverable, validated_choice, with_archive_members, @@ -100,7 +100,7 @@ class _EmulatorPackBuild: discrepancies: list[str] = field(default_factory=list) unsourceable_files: list[str] = field(default_factory=list) instruction_files: list[str] = field(default_factory=list) - placed: _Placed = field(default_factory=lambda: _Placed(True)) + placed: Placed = field(default_factory=lambda: Placed(True)) seen_hashes: set[str] = field(default_factory=set) # SHA1 dedup for same file, different path # Loose file packed at each folded destination, to tell a profile asking # for the same file there from one asking for other bytes. @@ -118,9 +118,9 @@ class _EmulatorPackBuild: def _add(self, local_path: str, dest: str, fe: dict | None) -> None: """Write a loose file or an archive at dest and count it.""" if fe is not None and local_path.endswith(".zip"): - _add_zip_to_pack(local_path, dest, self.zf, fe) + add_zip_to_pack(local_path, dest, self.zf, fe) else: - _add_pack_member(self.zf, local_path, dest) + add_pack_member(self.zf, local_path, dest) self.placed.take(dest) self.total_files += 1 if self.record is not None: @@ -156,7 +156,7 @@ class _EmulatorPackBuild: # Pack archives as units archive_prefix = profile.get("archive_prefix", "") for archive_name in sorted({fe["archive"] for fe in files if fe.get("archive")}): - archive_dest = _archive_destination( + archive_dest = archive_destination( archive_name, archive_prefix, pack_structure, self.standalone ) own_entry = archive_entry(archive_name, files) @@ -196,7 +196,7 @@ class _EmulatorPackBuild: # profile without its archive, which used to pass in # silence: a neocdz.zip lacking 000-lo.lo shipped as the # one the second core needs. - if not (taken and local_path and _same_bytes( + if not (taken and local_path and same_bytes( local_path, self.packed_at.get(archive_dest.lower()) )): return ([own_entry], False, functools.partial( @@ -223,7 +223,7 @@ class _EmulatorPackBuild: continue if fe.get("archive"): continue - dest = _resolve_destination(fe, self.standalone) + dest = resolve_destination(fe, self.standalone) if not dest or dest in spares: continue if self.region_drops and dest in self.region_drops: @@ -237,7 +237,7 @@ class _EmulatorPackBuild: self.placed.take(dest) instr = provided.get("instructions", "Please provide this file manually.") folder = dest.rsplit("/", 1)[0] + "/" if "/" in dest else "" - _write_generated_member( + write_generated_member( self.zf, f"{folder}INSTRUCTIONS_{provided['name']}.txt", f"File needed: {provided['name']}\n\n{instr}\n", @@ -314,7 +314,7 @@ class _EmulatorPackBuild: else None if chosen is not None else refused_path ) if chosen is not None or held is not None: - if block == "taken" and held and _same_bytes( + if block == "taken" and held and same_bytes( held, self.packed_at.get(dest.lower()) ): # The file already at this path, asked for twice. @@ -400,7 +400,7 @@ class _EmulatorPackBuild: prefix = pack_structure.get(mode_key, "") if prefix: dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix - self.data_files += _pack_data_tree( + self.data_files += pack_data_tree( self.zf, local_cache, dd_dest, self.placed.destinations, self.placed.parents, self.placed.lower, self.packed_at, ) @@ -441,7 +441,7 @@ class _EmulatorPackBuild: print( f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)" ) - _MISSING_DATA_DIRS.update(self.data_dir_notices) + MISSING_DATA_DIRS.update(self.data_dir_notices) def generate_emulator_pack( @@ -483,15 +483,15 @@ def generate_emulator_pack( record = options.get("record") # ZIP naming - display_names = [_name_part(p.get("emulator", n)) for n, p in selected] - validation_index = _build_validation_index(dict(selected)) + display_names = [file_name_part(p.get("emulator", n)) for n, p in selected] + validation_index = build_validation_index(dict(selected)) narrow_tags = "".join( tag - for tag, _label in _narrowings( + for tag, _label in pack_narrowings( "full", regions, None, False, required_only, standalone ) ) - zip_name = options.get("pack_name") or _bounded_pack_name( + zip_name = options.get("pack_name") or bounded_pack_name( display_names, [n for n, _p in selected], f"{narrow_tags}_BIOS_Pack.zip" ) zip_path = os.path.join(output_dir, zip_name) @@ -511,7 +511,7 @@ def generate_emulator_pack( ) with ( contextlib.nullcontext(record) if record is not None - else _writing_pack(zip_path) + else writing_pack(zip_path) ) as zf: build = _EmulatorPackBuild( db, bios_dir, standalone, required_only, zip_contents, data_registry, @@ -589,8 +589,8 @@ def generate_system_pack( # Named like the platform's --system tag: one spelling of a system is # one file name, and one selection. - sys_display = _bounded_join( - [_system_display_name(sid) for sid in system_ids], list(system_ids) + sys_display = bounded_join( + [system_display_name(sid) for sid in system_ids], list(system_ids) ) # Built in a scratch directory: under its emulator name in output_dir it # overwrote, then carried away, an --emulator pack already there. @@ -599,7 +599,7 @@ def generate_system_pack( # tag made --system X --required-only overwrite the pack built without it. tags = "".join( tag - for tag, _label in _narrowings( + for tag, _label in pack_narrowings( "full", regions, None, False, required_only, standalone=standalone ) ) @@ -634,7 +634,7 @@ def generate_system_pack( shutil.rmtree(scratch, ignore_errors=True) -def _system_display_name(system_id: str) -> str: +def system_display_name(system_id: str) -> str: """Convert system ID to display name for ZIP naming.""" s = system_id.lower().replace("_", "-") for prefix in MANUFACTURER_PREFIXES: diff --git a/scripts/packs/extras.py b/scripts/packs/extras.py index 7f8654682..a6b433b86 100644 --- a/scripts/packs/extras.py +++ b/scripts/packs/extras.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, TypedDict from core.options import reject_unknown from model.profiles import PROFILE_IDENTITY_FIELDS, entry_system_ids -from model.systems import _norm_system_id +from model.systems import norm_system_id from model.alternatives import core_file_spares, required_only_spares, set_fields from resolve.archives import archive_members, contents_members, holds_required_members from model.declarations import declared_root, expand_platform_declared_names, platform_declarations @@ -34,7 +34,7 @@ if TYPE_CHECKING: from typing_extensions import Unpack -def _detect_extras_prefix(config: dict, base_dest: str) -> str: +def detect_extras_prefix(config: dict, base_dest: str) -> str: """The prefix core-extra destinations take (may be empty). When base_destination is empty (RetroDECK), it is the dominant root of @@ -198,7 +198,7 @@ def _map_emulator_to_slug( sys_to_slug: dict[str, str], ) -> str: """Map an emulator to a destination slug for slug-based platforms.""" - from model.systems import _norm_system_id + from model.systems import norm_system_id emu_systems = set(profile.get("systems", [])) # Direct match @@ -208,7 +208,7 @@ def _map_emulator_to_slug( return sys_to_slug.get(target, "") # Normalized match for es in sorted(emu_systems): - norm = _norm_system_id(es) + norm = norm_system_id(es) if norm in norm_map: target = norm_map[norm] return sys_to_slug.get(target, "") @@ -404,7 +404,7 @@ def hidden_extras( ``required_only`` are the builder's for a --source truth or a --required-only pack: an optional extra is skipped before it takes a path. """ - from packs.paths import _register_path, placement_block + from packs.paths import register_path, placement_block reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__) report = options.get("report") @@ -423,14 +423,14 @@ def hidden_extras( parents: set[str] = set() content: dict[str, str | None] = {} for dest, local in shipped.items(): - _register_path(dest, seen, parents) + register_path(dest, seen, parents) content[dest.lower()] = sha1_by_path.get(local) lower = set(content) if case_insensitive else set() - prefix = _detect_extras_prefix(config, base_dest) + prefix = detect_extras_prefix(config, base_dest) region_prefix = declared_root(config) hidden: dict[tuple[str, str, str], str] = {} packed_keys: set[tuple[str, str, str]] = set() - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, emulators_dir, db, set() if system_ids else set(shipped), base_dest, profiles, target_cores=target_cores, include_all=include_all, undeclared=report, @@ -474,7 +474,7 @@ def hidden_extras( hidden.setdefault(key, reason) continue packed_keys.add(key) - _register_path(full, seen, parents) + register_path(full, seen, parents) content[full.lower()] = held if case_insensitive: lower.add(full.lower()) @@ -1275,9 +1275,9 @@ class ExtraPlacement: """ def __init__(self, config: dict, base_dest: str, profiles: dict) -> None: - from model.systems import _norm_system_id + from model.systems import norm_system_id - self.prefix = _detect_extras_prefix(config, base_dest) + self.prefix = detect_extras_prefix(config, base_dest) self.slug_based, self.sys_to_slug = _detect_slug_structure(config) self.platform_systems = set(config.get("systems", {}).keys()) self.native_systems = native_slug_systems(config) @@ -1289,7 +1289,7 @@ class ExtraPlacement: self.outer = {root for root in OUTER_ROOTS if outer_layout(config, root)} self.config = config self.norm_map = ( - {_norm_system_id(sid): sid for sid in self.platform_systems} + {norm_system_id(sid): sid for sid in self.platform_systems} if self.slug_based else {} ) @@ -1393,7 +1393,7 @@ def undeclared_report( target_cores: set[str] | None = None, include_all: bool = False, ) -> list[dict]: - """The gap report _collect_emulator_extras reads, for a caller that + """The gap report collect_emulator_extras reads, for a caller that collects the extras more than once with these arguments: the region grouping and the pack or manifest phase 2 each computed it in full.""" from packs.gaps import find_undeclared_files @@ -1406,7 +1406,7 @@ def undeclared_report( class CollectOptions(TypedDict, total=False): - """The records _collect_emulator_extras fills, and the report it reuses.""" + """The records collect_emulator_extras fills, and the report it reuses.""" claimants: dict[tuple[str, str, str], str] | None unplaceable: list[dict] | None @@ -1447,7 +1447,7 @@ class _CopyScope: extras_prefix: str -def _collect_emulator_extras( +def collect_emulator_extras( config: dict, emulators_dir: str, db: dict, @@ -1490,7 +1490,7 @@ def _collect_emulator_extras( Works for ANY platform (RetroArch, Batocera, Recalbox, etc.) """ - reject_unknown("_collect_emulator_extras", options, CollectOptions.__optional_keys__) + reject_unknown("collect_emulator_extras", options, CollectOptions.__optional_keys__) undeclared = options.get("undeclared") claimants = options.get("claimants") unplaceable = options.get("unplaceable") @@ -2042,25 +2042,25 @@ def _another_claim(extra: dict | None, claim: dict) -> None: claims.sort(key=lambda c: c["claim_order"]) -def _extra_system_ids(extra: dict) -> list[str]: +def extra_system_ids(extra: dict) -> list[str]: """Return the narrowest system ownership preserved on a core extra.""" explicit = extra.get("source_system") if explicit: return [str(explicit)] return [str(value) for value in extra.get("source_systems", []) if value] -def _serving_system_ids(extra: dict) -> list[str]: +def serving_system_ids(extra: dict) -> list[str]: """Every system the extra's file serves: its own core's and those of the other cores whose claim rides on it. One file stands per destination, so narrowed to any of their systems the file is what that core reads. """ - ids = list(_extra_system_ids(extra)) + ids = list(extra_system_ids(extra)) for claim in extra.get("other_claims", []): - ids.extend(s for s in _extra_system_ids(claim) if s not in ids) + ids.extend(s for s in extra_system_ids(claim) if s not in ids) return ids -def _kept(entries: list[dict], required_only: bool) -> list[dict]: +def kept_entries(entries: list[dict], required_only: bool) -> list[dict]: """The entries a pack keeps: optional ones go under --required-only.""" if not required_only: return entries @@ -2073,12 +2073,12 @@ def extras_for_systems(extras: list[dict], system_ids: list[str]) -> list[dict]: Extras carry their profile/system identity directly. Display labels are presentation only and must never drive routing. """ - wanted = set(system_ids) | {_norm_system_id(s) for s in system_ids} + wanted = set(system_ids) | {norm_system_id(s) for s in system_ids} return [ fe for fe in extras if ( - set(_serving_system_ids(fe)) - | {_norm_system_id(s) for s in _serving_system_ids(fe)} + set(serving_system_ids(fe)) + | {norm_system_id(s) for s in serving_system_ids(fe)} ) & wanted ] @@ -2187,7 +2187,7 @@ def platform_region_groups( members = groups.setdefault(sys_id, []) # Decided over what the pack keeps: an optional winner removed # afterwards left its slot empty. - for file_entry in _kept(system.get("files", []), required_only): + for file_entry in kept_entries(system.get("files", []), required_only): dest = declared_destination(file_entry) if dest: members.append((dest, file_entry.get("name", ""))) @@ -2203,7 +2203,7 @@ def platform_region_groups( return groups, extra_dests absent: list[dict] = [] - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, emulators_dir, db, @@ -2219,7 +2219,7 @@ def platform_region_groups( held = {id(extra) for extra in extras} spellings = system_spellings(systems) region_prefix = declared_root(config) - for extra in _kept(extras + absent, required_only): + for extra in kept_entries(extras + absent, required_only): dest = extra_region_key(extra, region_prefix) if not dest: continue @@ -2255,7 +2255,7 @@ def system_spellings(systems: Iterable[str]) -> dict[str, str]: """ spellings: dict[str, str] = {} for sys_id in sorted(systems): - spellings.setdefault(_norm_system_id(sys_id), sys_id) + spellings.setdefault(norm_system_id(sys_id), sys_id) return spellings @@ -2268,7 +2268,7 @@ def extra_region_groups( extra competes beside the files the platform declares for that system. """ def system_group(sys_id: str) -> str: - return (spellings or {}).get(_norm_system_id(sys_id), sys_id) + return (spellings or {}).get(norm_system_id(sys_id), sys_id) emulator = extra.get("source_emulator", "") variant = extra.get("selection_slot") @@ -2314,19 +2314,19 @@ def emulator_region_drops( emulator pack resolves with. """ from resolve import regions as resolve_regions - from packs.paths import _resolve_destination - from resolve.validation import _build_validation_index, filter_files_by_mode + from packs.paths import resolve_destination + from resolve.validation import build_validation_index, filter_files_by_mode region_index = resolve_regions.build_region_index(dict(selected)) region_groups: dict[str, list[tuple[str, str]]] = {} held: set[str] | None = set() if db is not None else None - validation_index = _build_validation_index(dict(selected)) if db is not None else {} + validation_index = build_validation_index(dict(selected)) if db is not None else {} for emu_name, profile in sorted(selected): # Decided over what the pack keeps, as on the platform side: an # optional winner removed afterwards left its slot empty. entries = filter_files_by_mode(profile.get("files", []), standalone) - for fe in _kept(entries, required_only): - dest = _resolve_destination(fe, standalone) + for fe in kept_entries(entries, required_only): + dest = resolve_destination(fe, standalone) if dest: group_id = _emulator_region_group(emu_name, profile, fe, dest) region_groups.setdefault(group_id, []).append( @@ -2362,7 +2362,7 @@ def emulator_required_spares( stvbios.zip. The pack and verify --emulator both read this.""" from model.alternatives import groups_of, rank_in, required_groups from resolve.archives import archive_entry - from packs.paths import _archive_destination, _resolve_destination + from packs.paths import archive_destination, resolve_destination reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__) data_registry = options.get("data_registry") @@ -2374,12 +2374,12 @@ def emulator_required_spares( archives.append(archive) own = archive_entry(archive, files) if groups_of(own): - candidates.append({"dest": _archive_destination( + candidates.append({"dest": archive_destination( archive, profile.get("archive_prefix", ""), profile.get("pack_structure"), standalone, ), "entry": own}) candidates.extend( - {"dest": _resolve_destination(fe, standalone), "entry": fe} + {"dest": resolve_destination(fe, standalone), "entry": fe} for fe in files if not fe.get("archive") and groups_of(fe) ) if not candidates: diff --git a/scripts/packs/finalize.py b/scripts/packs/finalize.py index 64ca77a23..714622550 100644 --- a/scripts/packs/finalize.py +++ b/scripts/packs/finalize.py @@ -17,16 +17,16 @@ from core.artifacts import set_plain_mode from core.options import reject_unknown from model.registry import list_registered_platforms from model.targets import load_target_config -from packs.archive import _write_generated_member +from packs.archive import write_generated_member from packs.integrity import generate_sha256sums, verify_pack, verify_pack_against_platform -from packs.naming import _expected_pack_names, _narrows_contents, _pack_archives +from packs.naming import expected_pack_names, narrows_contents, pack_archives from packs.scope import annotate_pack_systems if TYPE_CHECKING: from typing_extensions import Unpack -def _baseline_shortfall(excluded: int, absent: int) -> list[str]: +def baseline_shortfall(excluded: int, absent: int) -> list[str]: """Why a verified pack holds fewer baseline files than the platform declares.""" parts = [] if excluded: @@ -43,7 +43,7 @@ def inject_manifest(zip_path: str, manifest: dict) -> None: """Inject manifest.json into an existing ZIP pack. The pack is rewritten beside its final name and swapped in, as - _writing_pack builds it: appending in place rewrites the central + writing_pack builds it: appending in place rewrites the central directory last, so a process killed in between left an unreadable ZIP where a valid pack had been. """ @@ -64,7 +64,7 @@ def inject_manifest(zip_path: str, manifest: dict) -> None: # two different byte layouts depending on the path taken here. shutil.copyfile(zip_path, scratch) with zipfile.ZipFile(scratch, "a", zipfile.ZIP_DEFLATED) as zf: - _write_generated_member(zf, "manifest.json", manifest_json) + write_generated_member(zf, "manifest.json", manifest_json) else: with zipfile.ZipFile(zip_path, "r") as src, \ zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as dst: @@ -72,7 +72,7 @@ def inject_manifest(zip_path: str, manifest: dict) -> None: if item.filename == "manifest.json": continue dst.writestr(item, src.read(item.filename)) - _write_generated_member(dst, "manifest.json", manifest_json) + write_generated_member(dst, "manifest.json", manifest_json) set_plain_mode(scratch) os.replace(scratch, zip_path) except BaseException: @@ -149,7 +149,7 @@ def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> b ) status = "OK" if p_ok else "FAILED" exclusion_note = "".join( - f", {part}" for part in _baseline_shortfall(bl_excluded, bl_absent) + f", {part}" for part in baseline_shortfall(bl_excluded, bl_absent) ) print( f" platform {pname}: {bl_present}/{bl_checked} baseline present" @@ -192,11 +192,11 @@ def verify_and_finalize_packs( # substring: a _Custom or regional pack left by another run was judged # against this run's expectation and failed it. registered = list_registered_platforms(opts.platforms_dir) - expected = _expected_pack_names( + expected = expected_pack_names( registered, opts.platforms_dir, opts.regions, opts.target_name, no_game_data=opts.no_game_data, ) - packs = _pack_archives(output_dir) + packs = pack_archives(output_dir) if opts.built is not None: packs = [name for name in packs if name in set(opts.built)] pack_to_platform: dict[str, list[str]] = {} @@ -229,7 +229,7 @@ def verify_and_finalize_packs( # Skipped for filtered/split/custom packs (intentionally partial) if opts.skip_conformance: continue - if _narrows_contents(name): + if narrows_contents(name): continue for pname in pack_to_platform.get(name, []): if not _conforms(zip_path, pname, db, opts): diff --git a/scripts/packs/gaps.py b/scripts/packs/gaps.py index 9dcb4a456..15af0384d 100644 --- a/scripts/packs/gaps.py +++ b/scripts/packs/gaps.py @@ -17,10 +17,10 @@ from resolve.launchers import LauncherLayer, declared_destinations, held_record from resolve.layout import runs_standalone, system_dir_path from resolve.localfile import resolve_local_file from resolve.nativemode import hash_mismatch_excludes_file -from resolve.ownership import _foreign_tree, _owner_tokens +from resolve.ownership import foreign_tree, owner_tokens from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set from resolve.validation import ( - _parse_validation, + parse_validation, case_folded_slots, core_size_refusal, declaration_settles, @@ -56,7 +56,7 @@ def _build_expected(file_entry: dict, checks: list[str]) -> dict: def _in_foreign_tree(db: dict, owners: set[str], sha1: str) -> bool: """Whether the collection keeps this sha1 in another emulator's tree.""" - return _foreign_tree(db.get("files", {}).get(sha1, {}).get("path", ""), owners) + return foreign_tree(db.get("files", {}).get(sha1, {}).get("path", ""), owners) def _name_in_index( @@ -137,7 +137,7 @@ def _identity_of(entry: dict) -> dict: } -def _gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: +def gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: """The destination a gap entry is keyed and reported at.""" # One destination rule for the dedup key and for the entry: a # standalone build without standalone_path falls back on path. @@ -206,7 +206,7 @@ class _GapScan: """Consider one profile entry of one build as a gap.""" fname = f.get("name", "") save_root = read_from_save_dir(f, is_standalone) - dest = _gap_destination(f, fname, is_standalone, save_root) + dest = gap_destination(f, fname, is_standalone, save_root) region_key = _region_key(f) # Same-name requirements at different paths, for different systems, # or in distinct variant groups are not interchangeable. @@ -350,7 +350,7 @@ class _GapScan: _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) return _lp is not None and _st != "hash_mismatch" in_repo = self._held_by_name(owned, f, fname, dest) - if in_repo and "size" in _parse_validation(f.get("validation")): + if in_repo and "size" in parse_validation(f.get("validation")): # On any platform the core measures what it opens: a # copy it turns away by its own size check is not # held for it, the rule the builder's lookup applies @@ -364,7 +364,7 @@ class _GapScan: return in_repo def _held_by_name(self, owned: dict, f: dict, fname: str, dest: str) -> bool: - foreign = functools.partial(_in_foreign_tree, self.db, _owner_tokens(owned)) + foreign = functools.partial(_in_foreign_tree, self.db, owner_tokens(owned)) in_repo = _name_in_index( fname, self.by_name, self.by_path_suffix, self.data_names, self.by_name_lower, foreign, @@ -407,7 +407,7 @@ class _GapScan: self, emu_name: str, layout: dict, f: dict, fname: str, dest: str, in_repo: bool, save_root: bool, ) -> dict: - checks = _parse_validation(f.get("validation")) + checks = parse_validation(f.get("validation")) entry = { "profile": emu_name, "emulator": layout.get("emulator", emu_name), diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index 6b5cf1be8..b76bb7cb5 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -11,8 +11,8 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict from packs.verdicts import DEFAULT_BIOS_DIR -from core.artifacts import _build_timestamp -from packs.paths import MEDIA_MARKER, _has_path_conflict +from core.artifacts import build_timestamp +from packs.paths import MEDIA_MARKER, has_path_conflict from core.ziptools import build_zip_contents_index from core.ziptools import check_inside_zip from resolve.nativemode import digest_algorithm @@ -28,7 +28,7 @@ from model.profiles import load_emulator_profiles from model.platforms import load_platform_config import os from packs.extras import platform_region_groups -from packs.paths import _flat +from packs.paths import flat_arcname from resolve.nativemode import reads_file_contents from resolve import regions as resolve_regions from packs import slots @@ -237,7 +237,7 @@ def verify_pack( "schema_version": 1, "version": 1, "generator": "retrobios generate_pack.py", - "generated": _build_timestamp(db), + "generated": build_timestamp(db), "files": [], } errors: list[str] = [] @@ -595,7 +595,7 @@ def _builder_extras( there: taken by the refused file, that core file was never compared. """ from packs.extras import ExtraResolver, hidden_extras - from resolve.validation import _build_validation_index, destination_owners + from resolve.validation import build_validation_index, destination_owners config, emu_profiles = expect.config, expect.emu_profiles data_registry = expect.opts.data_registry @@ -632,7 +632,7 @@ def _builder_extras( expect.region_drops or None, resolver=ExtraResolver( db, DEFAULT_BIOS_DIR, build_zip_contents_index(db), data_registry, - _build_validation_index(platform_profiles), + build_validation_index(platform_profiles), destination_owners(platform_profiles), True, profiles=emu_profiles, ), placed_local=placed_local, @@ -855,7 +855,7 @@ def _count_baseline( member = expected elif expected.lower() in view.zip_lower: member = view.zip_lower[expected.lower()] - elif _has_path_conflict(expected, view.zip_set, view.zip_parents): + elif has_path_conflict(expected, view.zip_set, view.zip_parents): # Skipped by the builder for the same reason: not an error count.present += 1 continue @@ -967,7 +967,7 @@ def _check_core_extras( ) for full, local in sorted(placed_local.items()): core_checked += 1 - flat = _flat(full, expect.base_dest, view.is_flat) + flat = flat_arcname(full, expect.base_dest, view.is_flat) member = flat if flat in view.zip_set else view.zip_lower.get(flat.lower()) if member is None: errors.append(f"core missing: {full}") diff --git a/scripts/packs/manifest.py b/scripts/packs/manifest.py index adc5d0904..5ff7fb462 100644 --- a/scripts/packs/manifest.py +++ b/scripts/packs/manifest.py @@ -9,7 +9,7 @@ from collections.abc import Callable, Iterator from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict -from core.artifacts import _build_timestamp +from core.artifacts import build_timestamp from core.options import reject_unknown from core.paths import REPO_ROOT, declared_destination, sanitize_pack_path from model.declarations import OUTER_ROOTS, declared_root, outer_layout @@ -19,50 +19,50 @@ from model.registry import load_data_dir_registry from model.safeparse import yaml_load from model.systems import platform_system_names from packs import slots -from packs.archive import CASE_FOLDING_OS, PACK_DOCUMENTS, _Placed +from packs.archive import CASE_FOLDING_OS, PACK_DOCUMENTS, Placed from packs.datatrees import ( - _data_directory_members, - _in_data_cache, - _manifest_data_directories, + data_directory_members, + in_data_cache, + manifest_data_directories, core_data_trees, pack_markers, tree_readers, ) from packs.extras import ( - _collect_emulator_extras, + collect_emulator_extras, extra_region_key, save_entry_fields, save_manifest_dest, undeclared_report, ) from packs.manifestcores import ( - _downloaded_cores, - _manifest_core_entries, - _manifest_core_index, - _manifest_selection, - _offered_boards, + downloaded_cores, + manifest_core_entries, + manifest_core_index, + manifest_selection, + offered_boards, ) from packs.manifestentry import ( MANIFEST_OUTER_FIELDS, - _ClaimContext, - _attach_claims, - _manifest_dest_of, - _manifest_entry, - _record_absent, - _record_slot_choices, - _record_unplaceable, + ClaimContext, + attach_claims, + manifest_dest_of, + manifest_entry, + record_absent, + record_slot_choices, + record_unplaceable, ) from packs.manifestselect import SelectionIndex from packs.paths import save_layout from packs.scope import platform_list_version, system_titles -from packs.standalone import _standalone_copies, _standalone_layouts +from packs.standalone import standalone_copies, standalone_layouts from resolve.contentlayout import TARGET_KEY from resolve.cores import filter_systems_by_target, resolve_platform_cores as _platform_cores from resolve.gamedata import GAME_DATA, is_game_data, platform_game_data, without_game_data from resolve.nativemode import digest_algorithm, reads_file_contents from resolve.packfiles import preferred_entries as _preferred_entries, resolve_declaration from resolve.validation import ( - _build_validation_index, + build_validation_index, agnostic_substitute, baseline_verdict, destination_owners, @@ -148,7 +148,7 @@ class _ManifestBuild: manifest_validation: dict = field(default_factory=dict) manifest_owners: dict = field(default_factory=dict) game_destinations: set[str] = field(default_factory=set) - placed: _Placed = field(init=False) + placed: Placed = field(init=False) # Destination -> (entry, full destination, manifest destination) of each # platform file, for the core claims a target build would fall back on. platform_entries: dict[str, tuple[dict, str, str]] = field(default_factory=dict) @@ -177,7 +177,7 @@ class _ManifestBuild: data_directories: list[dict] = field(default_factory=list) def __post_init__(self) -> None: - self.placed = _Placed(self.case_insensitive) + self.placed = Placed(self.case_insensitive) @property def base_dest(self) -> str: @@ -197,7 +197,7 @@ class _ManifestBuild: return self.selection def manifest_destination(self, full_destination: str) -> str: - return _manifest_dest_of(full_destination, self.base_dest) + return manifest_dest_of(full_destination, self.base_dest) def record_omission( self, @@ -355,7 +355,7 @@ class _ManifestBuild: local_path: str, settle: _Settle, ) -> None: - entry, file_size = _manifest_entry( + entry, file_size = manifest_entry( local_path, dest, None, self.db, self.repo_root, self.fields.fields(dest, file_entry["name"]), ) @@ -364,14 +364,14 @@ class _ManifestBuild: if entry is not None and self.opts.target_cores is None: order = self.declaration_order(full_dest) if full_dest in self.slot_choices or len(order) > 1: - _record_slot_choices( + record_slot_choices( entry, self.slot_choices.get(full_dest, []), order, settle, dest, self.db, self.repo_root, ) if entry is None: self.record_omission(full_dest, file_entry, sys_id, "not_found", None) if file_size and full_dest not in self.placed.destinations: - if _in_data_cache(local_path, self.data_registry): + if in_data_cache(local_path, self.data_registry): self.cache_held[full_dest] = (local_path, file_size) else: self.pack_only_sizes.append(file_size) @@ -384,8 +384,8 @@ class _ManifestBuild: self.total_size += file_size self.placed.take(full_dest) - def claim_context(self) -> _ClaimContext: - return _ClaimContext( + def claim_context(self) -> ClaimContext: + return ClaimContext( self.db, self.bios_dir, self.zip_contents, self.opts.offline, self.opts.required_only, self.manifest_validation, self.manifest_owners, self.repo_root, self.data_registry, @@ -398,7 +398,7 @@ class _ManifestBuild: baseline_claims: dict[str, dict] = {} absent: list[dict] = [] if opts.source != "platform": - core_files = _collect_emulator_extras( + core_files = collect_emulator_extras( self.config, opts.emulators_dir, self.db, @@ -414,12 +414,12 @@ class _ManifestBuild: ) else: core_files = [] - _record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles) - _record_absent( + record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles) + record_absent( absent, self.config, self.base_dest, self.region_drops, opts.required_only, self.placed.destinations, self.omitted_by_destination, self.record_omission, ) - self.total_size += _manifest_core_entries( + self.total_size += manifest_core_entries( core_files, self.config, self.db, self.bios_dir, self.base_dest, self.repo_root, self.zip_contents, opts.offline, region_drops=self.region_drops, case_insensitive=self.case_insensitive, @@ -445,7 +445,7 @@ class _ManifestBuild: # still fills it. entry.pop("category", None) if claims: - _attach_claims(entry, claims, ctx, dest, dest) + attach_claims(entry, claims, ctx, dest, dest) # A platform omission narrows like a platform file: by the systems # declaring it, which can be fewer than the ones whose cores read it. for full_dest, omission in self.omitted_by_destination.items(): @@ -471,7 +471,7 @@ class _ManifestBuild: core_trees = ([] if opts.source == "platform" else core_data_trees(self.config, self.emu_profiles, self.platform_name, self.data_registry, opts.target_cores)) - self.data_members = list(_data_directory_members( + self.data_members = list(data_directory_members( self.pack_systems, self.data_registry, self.platform_name, self.base_dest, self.case_insensitive, self.placed.destinations, self.placed.lower, self.placed.parents, refs_out=data_refs, required_only=required_only, @@ -486,7 +486,7 @@ class _ManifestBuild: self.pack_only_sizes.append(size) else: self.omitted_by_destination.pop(full_dest, None) - self.data_directories = _manifest_data_directories( + self.data_directories = manifest_data_directories( self.data_members, data_refs, self.data_registry or {}, self.base_dest, tree_readers(self.pack_systems, core_trees), self.pack_systems, ) @@ -499,7 +499,7 @@ class _ManifestBuild: # The pack is unzipped into the BIOS folder: an entry the installer puts # in the roms, emulators or configs folder is in its list, not in the ZIP. outer = [e for e in manifest_files if e.get("root") in OUTER_ROOTS] - core_names, system_cores = _manifest_core_index( + core_names, system_cores = manifest_core_index( config, self.emu_profiles, manifest_files, list(omitted.values()) ) result: dict = { @@ -521,10 +521,10 @@ class _ManifestBuild: "platform": platform_name, "display_name": config.get("platform", platform_name), "version": platform_list_version(config, platform_name), - "generated": _build_timestamp(self.db), + "generated": build_timestamp(self.db), "base_destination": self.base_dest, "detect": self.install_section.get("detect", []), - "standalone_copies": _standalone_copies( + "standalone_copies": standalone_copies( self.install_section.get("standalone_copies", []), self.manifest_profiles, manifest_files, ), @@ -542,10 +542,10 @@ class _ManifestBuild: omitted.values(), key=lambda entry: entry["dest"] ), "core_names": core_names, - **({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores( + **({"downloaded_cores": downloaded} if (downloaded := downloaded_cores( config, self.emu_profiles, core_names, self.platforms_dir, )) else {}), - **({"offered_boards": offered} if (offered := _offered_boards( + **({"offered_boards": offered} if (offered := offered_boards( config, self.emu_profiles, core_names, [*manifest_files, *omitted.values()], )) else {}), @@ -634,7 +634,7 @@ def _start_manifest( name: emu_profiles[name] for name in _platform_cores(config, emu_profiles) } - build.manifest_validation = _build_validation_index(build.manifest_profiles) + build.manifest_validation = build_validation_index(build.manifest_profiles) build.manifest_owners = destination_owners(build.manifest_profiles) _settle_manifest_scope(build) return build, full_profiles @@ -679,7 +679,7 @@ def _settle_manifest_scope(build: _ManifestBuild) -> None: if opts.source != "platform" else None ) - build.region_drops, build.selection, build.builder_held = _manifest_selection( + build.region_drops, build.selection, build.builder_held = manifest_selection( config, build.pack_systems, opts.emulators_dir, build.db, build.base_dest, emu_profiles, opts.target_cores, opts.source, required_only=opts.required_only, regions=opts.regions, @@ -822,7 +822,7 @@ def generate_install_list( **truth_options, known_slot_choices=built["slot_choices"], ) _mark_truth(result, truth) - layouts = _standalone_layouts( + layouts = standalone_layouts( built["profiles"], settings.emulators_dir, db, bios_dir, settings.zip_contents or {}, settings.offline, platforms_dir, result, ) diff --git a/scripts/packs/manifestcores.py b/scripts/packs/manifestcores.py index ee43e9e28..9c6fa6bd2 100644 --- a/scripts/packs/manifestcores.py +++ b/scripts/packs/manifestcores.py @@ -14,8 +14,8 @@ from model.profiles import upstream_profile_index from model.targets import list_available_targets, load_target_config from packs.extras import ( ExtraResolver, - _detect_extras_prefix, - _extra_system_ids, + detect_extras_prefix, + extra_system_ids, extra_full_destination, extra_region_key, platform_region_groups, @@ -23,18 +23,18 @@ from packs.extras import ( save_manifest_dest, ) from packs.manifestentry import ( - _ClaimContext, - _attach_claims, - _claim_cores, - _claim_platform_omission, - _manifest_dest_of, - _manifest_entry, + ClaimContext, + attach_claims, + claim_cores, + claim_platform_omission, + manifest_dest_of, + manifest_entry, ) from packs.manifestselect import SelectionIndex -from packs.paths import _register_path, placement_block -from packs.platformpack import _slot_drops +from packs.paths import register_path, placement_block +from packs.platformpack import one_per_slot_drops from resolve import regions as resolve_regions, slot as slot_mod -from resolve.contentlayout import TARGET_KEY, _core_key, content_folder_boards +from resolve.contentlayout import TARGET_KEY, core_key, content_folder_boards from resolve.cores import ( downloadable_on, downloaded_only_profiles, @@ -48,7 +48,7 @@ if TYPE_CHECKING: class _CoreEntryState(TypedDict): - """What _manifest_core_entries reads and fills of the manifest being listed.""" + """What manifest_core_entries reads and fills of the manifest being listed.""" region_drops: set case_insensitive: bool @@ -63,7 +63,7 @@ class _CoreEntryState(TypedDict): class _CoreEntryParts(_CoreEntryState, total=False): - """_CoreEntryState and the optional keywords of _manifest_core_entries.""" + """_CoreEntryState and the optional keywords of manifest_core_entries.""" required_only: bool validation_index: dict | None @@ -78,14 +78,14 @@ class _CoreEntryLister: config: dict base_dest: str - ctx: _ClaimContext + ctx: ClaimContext state: _CoreEntryParts resolver: ExtraResolver total_size: int = 0 extras_pfx: str = field(init=False) def __post_init__(self) -> None: - self.extras_pfx = _detect_extras_prefix(self.config, self.base_dest) + self.extras_pfx = detect_extras_prefix(self.config, self.base_dest) def region_key(self, fe: dict) -> str: return extra_region_key(fe, declared_root(self.config)) @@ -139,7 +139,7 @@ class _CoreEntryLister: save_root = fe.get("root") == "save" folded = ( save_manifest_dest(fe) if save_root - else _manifest_dest_of(full_dest, self.base_dest) + else manifest_dest_of(full_dest, self.base_dest) ).lower() held = next( (e for e in self.state["manifest_files"] @@ -148,16 +148,16 @@ class _CoreEntryLister: None, ) if held is not None and held.get("cores") is not None: - _attach_claims(held, [fe], self.ctx, dest, held["dest"]) + attach_claims(held, [fe], self.ctx, dest, held["dest"]) def _omit(self, fe: dict, full_dest: str, reason: str) -> None: source_emu = fe.get("source_profile") or fe.get("source_emulator", "") - if not _claim_platform_omission( + if not claim_platform_omission( self.state["omitted_by_destination"].get(full_dest), source_emu ): - systems = _extra_system_ids(fe) + systems = extra_system_ids(fe) self.state["record_omission"]( - full_dest, fe, systems[0] if systems else "", reason, _claim_cores(fe), + full_dest, fe, systems[0] if systems else "", reason, claim_cores(fe), ) def _list_held( @@ -178,9 +178,9 @@ class _CoreEntryLister: # Relative to the roms or emulators folder the entry names. manifest_dest = dest else: - manifest_dest = _manifest_dest_of(full_dest, self.base_dest) + manifest_dest = manifest_dest_of(full_dest, self.base_dest) - entry, file_size = _manifest_entry( + entry, file_size = manifest_entry( local_path, manifest_dest, [source_emu] if source_emu else [], self.ctx.db, self.ctx.repo_root, state["selection"].fields(region_key, fe.get("name", "")), @@ -199,7 +199,7 @@ class _CoreEntryLister: is_game_data(claim) for claim in fe.get("other_claims", []) ): entry["category"] = GAME_DATA - _attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest) + attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest) state["manifest_files"].append(entry) displaced = state["omitted_by_destination"].pop(full_dest, None) @@ -212,12 +212,12 @@ class _CoreEntryLister: ) self.total_size += file_size state["seen_destinations"].add(full_dest) - _register_path(full_dest, state["seen_destinations"], state["seen_parents"]) + register_path(full_dest, state["seen_destinations"], state["seen_parents"]) if state["case_insensitive"]: state["seen_lower"].add(full_dest.lower()) -def _manifest_core_entries( +def manifest_core_entries( core_files: list, config: dict, db: dict, @@ -236,11 +236,11 @@ def _manifest_core_entries( Returns the bytes added. """ reject_unknown( - "_manifest_core_entries", state, + "manifest_core_entries", state, _CoreEntryParts.__required_keys__ | _CoreEntryParts.__optional_keys__, ) required_only = state.get("required_only", False) - ctx = _ClaimContext( + ctx = ClaimContext( db, bios_dir, zip_contents, offline, required_only, state.get("validation_index"), state.get("owners"), repo_root, state.get("data_registry"), @@ -261,7 +261,7 @@ def _manifest_core_entries( class _SelectionOptions(TypedDict, total=False): - """The keyword options of _manifest_selection.""" + """The keyword options of manifest_selection.""" required_only: bool regions: list[str] | None @@ -272,7 +272,7 @@ class _SelectionOptions(TypedDict, total=False): one_per_slot: bool -def _manifest_selection( +def manifest_selection( config: dict, pack_systems: dict, emulators_dir: str, @@ -290,7 +290,7 @@ def _manifest_selection( decides on the full manifest withdraws what `--region` and `--one-per-slot` withdraw from the pack. """ - reject_unknown("_manifest_selection", options, _SelectionOptions.__optional_keys__) + reject_unknown("manifest_selection", options, _SelectionOptions.__optional_keys__) required_only = options.get("required_only", False) regions = options.get("regions") one_per_slot = options.get("one_per_slot", False) @@ -323,7 +323,7 @@ def _manifest_selection( else set() ) if one_per_slot: - drops = drops | _slot_drops( + drops = drops | one_per_slot_drops( config, emu_profiles, target_cores, region_groups, drops, held )[0] return drops, SelectionIndex.build( @@ -333,7 +333,7 @@ def _manifest_selection( ), held -def _offered_boards( +def offered_boards( config: dict, profiles: dict[str, dict], core_names: dict[str, list[str]], @@ -354,18 +354,18 @@ def _offered_boards( pairs = content_folder_boards(config) if all(on is None for on in pairs.values()): return {} - from resolve.launchers import _roms_place + from resolve.launchers import roms_place_of by_key: dict[str, set[str]] = {} for name, claimants in upstream_profile_index(profiles).items(): - by_key.setdefault(_core_key(name), set()).update(claimants) + by_key.setdefault(core_key(name), set()).update(claimants) free = { (profile, folder) for (core, folder), on in pairs.items() if on is None for profile in by_key.get(core, ()) } found: dict[tuple[str, str, str], set[str]] = {} for (core, folder), on in pairs.items(): - where = _roms_place(config, folder) if on is not None else None + where = roms_place_of(config, folder) if on is not None else None if where is None: continue for profile in by_key.get(core, ()): @@ -392,7 +392,7 @@ def _offered_boards( return result -def _downloaded_cores( +def downloaded_cores( config: dict, profiles: dict[str, dict], core_names: dict[str, list[str]], @@ -425,7 +425,7 @@ def _downloaded_cores( return {profile: sorted(names) for profile, names in sorted(boards.items())} -def _manifest_core_index( +def manifest_core_index( config: dict, profiles: dict[str, dict], files: list[dict], diff --git a/scripts/packs/manifestentry.py b/scripts/packs/manifestentry.py index d93ba4e1f..104f3f51c 100644 --- a/scripts/packs/manifestentry.py +++ b/scripts/packs/manifestentry.py @@ -12,8 +12,8 @@ from core.paths import declared_destination from model.declarations import OUTER_ROOTS, declared_root from model.largefiles import asset_name, load_registered_paths, published_asset_name from packs.extras import ( - _detect_extras_prefix, - _extra_system_ids, + detect_extras_prefix, + extra_system_ids, extra_full_destination, extra_region_key, save_manifest_dest, @@ -124,7 +124,7 @@ def _stable_hashes(local_path: str, db: dict) -> dict: ) -def _manifest_entry( +def manifest_entry( local_path: str | None, dest: str, cores: list[str] | None, @@ -192,7 +192,7 @@ def _is_program(path: str) -> bool: @dataclass(frozen=True) -class _ClaimContext: +class ClaimContext: """How a manifest resolves and judges the copy a core claim names.""" db: dict @@ -206,10 +206,10 @@ class _ClaimContext: data_registry: dict | None = None -def _attach_claims( +def attach_claims( entry: dict, claims: list[dict], - ctx: _ClaimContext, + ctx: ClaimContext, dest: str, manifest_dest: str, ) -> None: @@ -248,7 +248,7 @@ def _attach_claims( claim, claim_path, ctx.db, ctx.validation_index or {}, ctx.bios_dir, None, claim.get("layout_path") or dest, ctx.owners, ) - copy, _size = _manifest_entry( + copy, _size = manifest_entry( claim_path, manifest_dest, [claim_emu], ctx.db, ctx.repo_root, {} ) if copy is None: @@ -267,7 +267,7 @@ def _attach_claims( def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict: """The omission a claim with nothing held stands for.""" - systems = _extra_system_ids(claim) + systems = extra_system_ids(claim) return { "name": str(claim.get("name") or ""), "system": systems[0] if systems else "", @@ -281,7 +281,7 @@ def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict: } -def _record_slot_choices( +def record_slot_choices( entry: dict, choices: list[tuple[str, str | None]], declarations: list[tuple[list[str], dict, str]], @@ -303,7 +303,7 @@ def _record_slot_choices( local_path, _status = settle(file_entry, sys_id, dest, override) if local_path is None: return None - copy, _size = _manifest_entry(local_path, dest, None, db, repo_root, {}) + copy, _size = manifest_entry(local_path, dest, None, db, repo_root, {}) if copy is None: return None return {k: v for k, v in copy.items() if k not in ("dest", "cores")} @@ -341,14 +341,14 @@ def _record_slot_choices( entry["declared_choices"] = declared -def _manifest_dest_of(full_dest: str, base_dest: str) -> str: +def manifest_dest_of(full_dest: str, base_dest: str) -> str: """A pack destination as the manifest writes it, below base_destination.""" if base_dest and full_dest.startswith(f"{base_dest}/"): return full_dest[len(base_dest) + 1:] return full_dest -def _claim_platform_omission(held: dict | None, emulator: str) -> bool: +def claim_platform_omission(held: dict | None, emulator: str) -> bool: """Record a core's claim on a destination the platform already omits. The platform's own omission stands while one of its declaring systems @@ -365,7 +365,7 @@ def _claim_platform_omission(held: dict | None, emulator: str) -> bool: return True -def _claim_cores(fe: dict) -> list[str]: +def claim_cores(fe: dict) -> list[str]: """The cores an extra and the claims folded onto it name: an omission names every core reading the file, as a list built for one of them would.""" @@ -376,7 +376,7 @@ def _claim_cores(fe: dict) -> list[str]: return sorted(name for name in names if name) -def _record_absent( +def record_absent( absent: list[dict], config: dict, base_dest: str, @@ -392,7 +392,7 @@ def _record_absent( pak000-004 reached no safety notice: the installer said everything was verified and the game refused to start. """ - extras_pfx = _detect_extras_prefix(config, base_dest) + extras_pfx = detect_extras_prefix(config, base_dest) for fe in absent: if required_only and fe.get("required") is False: continue @@ -414,7 +414,7 @@ def _record_absent( and source_emu not in claimed): held["cores"] = sorted([*claimed, source_emu]) continue - systems = _extra_system_ids(fe) + systems = extra_system_ids(fe) record_omission( full_dest, fe, systems[0] if systems else "", "not_found", [source_emu] if source_emu else [], @@ -429,7 +429,7 @@ def _record_absent( MANIFEST_OUTER_FIELDS = ("bios_folder", "from_bios", "searched", "default", "config") -def _record_unplaceable( +def record_unplaceable( unplaceable: list[dict], record_omission: Callable[..., None], config: dict, diff --git a/scripts/packs/manifestselect.py b/scripts/packs/manifestselect.py index b02bab533..13ce792a1 100644 --- a/scripts/packs/manifestselect.py +++ b/scripts/packs/manifestselect.py @@ -19,11 +19,11 @@ from dataclasses import dataclass from resolve import regions as resolve_regions from resolve import slot as slot_mod -from model.systems import _norm_system_id +from model.systems import norm_system_id from core.paths import declared_destination from packs.extras import ( - _kept, - _serving_system_ids, + kept_entries, + serving_system_ids, extra_region_groups, extra_region_key, system_spellings, @@ -54,11 +54,11 @@ class SelectionIndex: ) -> SelectionIndex: by_norm: dict[str, set[str]] = {} for sys_id in pack_systems: - by_norm.setdefault(_norm_system_id(sys_id), set()).add(sys_id) + by_norm.setdefault(norm_system_id(sys_id), set()).add(sys_id) declared_by: dict[str, set[str]] = {} for sys_id, system in pack_systems.items(): - for file_entry in _kept(system.get("files", []), required_only): + for file_entry in kept_entries(system.get("files", []), required_only): dest = declared_destination(file_entry) if dest: declared_by.setdefault(dest, set()).add(sys_id) @@ -76,9 +76,9 @@ class SelectionIndex: ) # A profile system the platform does not have is no system the # pack's --system accepts: it would offer what the pack refuses. - for sys_id in _serving_system_ids(extra): + for sys_id in serving_system_ids(extra): owned_by.setdefault(dest, set()).update( - by_norm.get(_norm_system_id(sys_id), ()) + by_norm.get(norm_system_id(sys_id), ()) ) systems_by_dest = { diff --git a/scripts/packs/md5pack.py b/scripts/packs/md5pack.py index 44f014f21..aa90337eb 100644 --- a/scripts/packs/md5pack.py +++ b/scripts/packs/md5pack.py @@ -11,9 +11,9 @@ from typing import TYPE_CHECKING, TypedDict from core.options import reject_unknown from model.platforms import load_platform_config from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles -from packs.archive import _add_pack_member, _writing_pack -from packs.naming import _name_part, _narrowings -from packs.paths import _resolve_destination +from packs.archive import add_pack_member, writing_pack +from packs.naming import file_name_part, pack_narrowings +from packs.paths import resolve_destination from resolve.packfiles import resolve_file, sha1_for_hash if TYPE_CHECKING: @@ -134,7 +134,7 @@ def _md5_pack_name( # take the name of a run without it. custom_tags = "".join( tag - for tag, _label in _narrowings( + for tag, _label in pack_narrowings( "full", None, None, False, False, standalone=opts.standalone ) ) @@ -144,7 +144,7 @@ def _md5_pack_name( "\n".join(sorted(f"{kind}:{value.lower()}" for kind, value in hashes)).encode() ).hexdigest()[:8] return ( - f"{_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}" + f"{file_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}" "_BIOS_Pack.zip" ) @@ -166,7 +166,7 @@ def _md5_destination(entry: dict, layout: _Md5Layout, opts: _Md5Settings) -> str if opts.emulator_name: # Laid out as the emulator pack lays it out: its path and # its standalone_path, which --standalone has to reach. - dest = _resolve_destination(matched_fe, opts.standalone) + dest = resolve_destination(matched_fe, opts.standalone) else: dest = matched_fe.get("destination", matched_fe.get("name", name)) elif paths: @@ -202,7 +202,7 @@ def generate_md5_pack( not_in_db: list[str] = [] seen: set[str] = set() - with _writing_pack(zip_path) as zf: + with writing_pack(zip_path) as zf: for hash_type, hash_val in hashes: sha1 = sha1_for_hash(hash_type, hash_val, db) if not sha1: @@ -225,7 +225,7 @@ def generate_md5_pack( not_in_repo.append((name, hash_val)) continue - _add_pack_member(zf, local_path, full_dest) + add_pack_member(zf, local_path, full_dest) packed.append((name, hash_val)) total = len(hashes) diff --git a/scripts/packs/naming.py b/scripts/packs/naming.py index 3a1e1915a..5faaa056d 100644 --- a/scripts/packs/naming.py +++ b/scripts/packs/naming.py @@ -15,7 +15,7 @@ from packs import parts as packs_parts from resolve.grouping import group_identical_platforms -def _narrowings( +def pack_narrowings( source: str, regions: list[str] | None, target_name: str | None, @@ -69,7 +69,7 @@ def _target_tag(target_name: str) -> str: ) -def _platform_target( +def platform_target( platform_name: str, target: str | None, platforms_dir: str ) -> str | None: """The target as this platform files it, the name its artifacts carry. @@ -86,7 +86,7 @@ def _platform_target( return canonical_target_name([platform_name], target, platforms_dir) -def _system_tag(system_filter: list[str] | None) -> str: +def system_tag(system_filter: list[str] | None) -> str: """Filename tag for a pack limited to some systems, empty for all.""" if not system_filter: return "" @@ -98,7 +98,7 @@ def _system_tag(system_filter: list[str] | None) -> str: s = s[len(prefix) :] break display_parts.append("_".join(p.title() for p in s.split("-") if p)) - return "_" + _bounded_join(display_parts, system_filter) + return "_" + bounded_join(display_parts, system_filter) # A system list long enough to push a pack name past this falls back to the @@ -106,7 +106,7 @@ def _system_tag(system_filter: list[str] | None) -> str: MAX_SYSTEM_TAG_BYTES = 120 -def _bounded_join(parts: list[str], keys: list[str]) -> str: +def bounded_join(parts: list[str], keys: list[str]) -> str: """Parts joined while they fit, else the first, a count and a digest. Thirty systems joined made a 261-byte file name and the ZIP could not @@ -125,7 +125,7 @@ def _bounded_join(parts: list[str], keys: list[str]) -> str: _UNSAFE_IN_NAME = re.compile(r'[/\\:*?"<>|]') -def _name_part(text: str, space: str = "") -> str: +def file_name_part(text: str, space: str = "") -> str: """A display name made safe to stand in a file name. 'FinalBurn Neo (CPS-1/CPS-2)' named a directory that did not exist, and a @@ -134,7 +134,7 @@ def _name_part(text: str, space: str = "") -> str: return _UNSAFE_IN_NAME.sub("-", text.replace(" ", space)) -def _platform_pack_stem( +def platform_pack_stem( group_platforms: list[str], representative: str, platforms_dir: str ) -> str: """Platform part of a pack name, version included. @@ -144,7 +144,7 @@ def _platform_pack_stem( """ rep_cfg = load_platform_config(representative, platforms_dir) version = rep_cfg.get("version", rep_cfg.get("dat_version", "")) - version_tag = f"_{_name_part(str(version))}" if version else "" + version_tag = f"_{file_name_part(str(version))}" if version else "" return platform_pack_prefix(group_platforms, representative, platforms_dir) + version_tag @@ -158,15 +158,15 @@ def platform_pack_prefix( """ if len(group_platforms) <= 1: rep_cfg = load_platform_config(representative, platforms_dir) - return _name_part(rep_cfg.get("platform", representative), "_") + return file_name_part(rep_cfg.get("platform", representative), "_") names = [ load_platform_config(p, platforms_dir).get("platform", p) for p in group_platforms ] - return "_".join(_name_part(n) for n in names) + return "_".join(file_name_part(n) for n in names) -def _platform_pack_name( +def platform_pack_name( platform_name: str, platforms_dir: str, narrowings: list[tuple[str, str]], @@ -179,9 +179,9 @@ def _platform_pack_name( """ if pack_name: return pack_name - stem = _platform_pack_stem([platform_name], platform_name, platforms_dir) + stem = platform_pack_stem([platform_name], platform_name, platforms_dir) tags = "".join(tag for tag, _label in narrowings) - return f"{stem}{tags}_BIOS_Pack{_system_tag(system_filter)}.zip" + return f"{stem}{tags}_BIOS_Pack{system_tag(system_filter)}.zip" # A file name holds 255 bytes on every filesystem a pack is written to, @@ -189,7 +189,7 @@ def _platform_pack_name( MAX_PACK_NAME_BYTES = 200 -def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -> str: +def bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -> str: """The emulator pack's file name, its emulators joined while they fit. Past the limit the name keeps the first emulator, says how many more the @@ -203,7 +203,7 @@ def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) - return f"{display_names[0]}_and_{len(display_names) - 1}_more_{digest}{suffix}" -def _expected_pack_names( +def expected_pack_names( platforms: list[str], platforms_dir: str, regions: list[str] | None, @@ -220,11 +220,11 @@ def _expected_pack_names( the (source, required_only) combinations the run built. """ def narrow_tags(platform_name: str) -> list[str]: - named = _platform_target(platform_name, target_name, platforms_dir) + named = platform_target(platform_name, target_name, platforms_dir) return [ "".join( tag - for tag, _label in _narrowings( + for tag, _label in pack_narrowings( source, regions, named, False, required, no_game_data=no_game_data ) ) @@ -233,7 +233,7 @@ def _expected_pack_names( names: dict[str, set[str]] = { p: { - f"{_platform_pack_stem([p], p, platforms_dir)}{tags}_BIOS_Pack.zip" + f"{platform_pack_stem([p], p, platforms_dir)}{tags}_BIOS_Pack.zip" for tags in narrow_tags(p) } for p in platforms @@ -255,7 +255,7 @@ def _expected_pack_names( ): if len(group) < 2: continue - stem = _platform_pack_stem(group, representative, platforms_dir) + stem = platform_pack_stem(group, representative, platforms_dir) for tags in narrow_tags(representative): for p in group: if p in names: @@ -281,7 +281,7 @@ def _content_narrowing_tags() -> tuple[str, ...]: for source, one_per_slot, required_only in dimensions: tags.extend( tag - for tag, _label in _narrowings(source, None, None, one_per_slot, required_only) + for tag, _label in pack_narrowings(source, None, None, one_per_slot, required_only) ) return tuple(tags) @@ -289,7 +289,7 @@ def _content_narrowing_tags() -> tuple[str, ...]: _CONTENT_NARROWING_TAGS = _content_narrowing_tags() -def _narrows_contents(pack_name: str) -> bool: +def narrows_contents(pack_name: str) -> bool: """True when a pack holds fewer files than the platform declares. A source-restricted or required-only build is narrower by design, so the @@ -300,15 +300,15 @@ def _narrows_contents(pack_name: str) -> bool: return any(f"{tag}_" in pack_name for tag in _CONTENT_NARROWING_TAGS) -def _pack_variant(pack_name: str) -> tuple[str, bool] | None: +def pack_variant(pack_name: str) -> tuple[str, bool] | None: """The (source, required_only) a pack was built as, read from its name. None for a one-per-slot pack, whose slot choice the check does not - replay. The tags come from the name builder, as for _narrows_contents. + replay. The tags come from the name builder, as for narrows_contents. """ def tagged(**dimension: object) -> bool: tags = [ - tag for tag, _label in _narrowings( + tag for tag, _label in pack_narrowings( str(dimension.get("source", "full")), None, None, bool(dimension.get("one_per_slot", False)), bool(dimension.get("required_only", False)), @@ -324,7 +324,7 @@ def _pack_variant(pack_name: str) -> tuple[str, bool] | None: return source, tagged(required_only=True) -def _pack_archives(output_dir: str) -> list[str]: +def pack_archives(output_dir: str) -> list[str]: """The ZIPs of a directory that are packs. A part of a split pack holds a share of a platform by design and was diff --git a/scripts/packs/paths.py b/scripts/packs/paths.py index f24869441..69a9be2cd 100644 --- a/scripts/packs/paths.py +++ b/scripts/packs/paths.py @@ -151,7 +151,7 @@ def _path_parents(dest: str) -> list[str]: parts = dest.split("/") return ["/".join(parts[:i]) for i in range(1, len(parts))] -def _has_path_conflict(dest: str, seen_files: set[str], seen_parents: set[str]) -> bool: +def has_path_conflict(dest: str, seen_files: set[str], seen_parents: set[str]) -> bool: """Check if dest conflicts with existing paths (file vs directory). Returns True if adding dest would create an impossible extraction: @@ -179,12 +179,12 @@ def placement_block( return "taken" if case_insensitive and dest.lower() in seen_lower: return "case_twin" - if _has_path_conflict(dest, seen_files, seen_parents): + if has_path_conflict(dest, seen_files, seen_parents): return "path_conflict" return None -def _register_path(dest: str, seen_files: set[str], seen_parents: set[str]) -> None: +def register_path(dest: str, seen_files: set[str], seen_parents: set[str]) -> None: """Track a file path and its parent directories.""" seen_files.add(dest) for parent in _path_parents(dest): @@ -207,13 +207,13 @@ def lands_on_android(target_names: Iterable[str], target: str | None) -> bool: return any(name.startswith("android") for name in target_names) -def _flat(arcname: str, prefix: str, flatten: bool) -> str: +def flat_arcname(arcname: str, prefix: str, flatten: bool) -> str: """Strip base_destination prefix from ZIP arcname when flattening.""" if flatten and prefix and arcname.startswith(prefix + "/"): return arcname[len(prefix) + 1:] return arcname -def _resolve_destination(file_entry: dict, standalone: bool) -> str: +def resolve_destination(file_entry: dict, standalone: bool) -> str: """Resolve the ZIP destination path for a file entry. ``path:`` is where the libretro build reads the file from the system @@ -241,7 +241,7 @@ def _resolve_destination(file_entry: dict, standalone: bool) -> str: return dest -def _archive_destination( +def archive_destination( archive_name: str, archive_prefix: str, pack_structure: dict | None, standalone: bool ) -> str: """Where an emulator pack places one of the profile's archives.""" diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index 91af98849..06745fea2 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -24,29 +24,29 @@ from packs import slots from packs.archive import ( CASE_FOLDING_OS, PackRecord, - _Placed, - _add_pack_member, - _add_zip_to_pack, - _extract_zip_to_archive, - _same_bytes, - _write_generated_member, - _writing_pack, + Placed, + add_pack_member, + add_zip_to_pack, + extract_zip_to_archive, + same_bytes, + write_generated_member, + writing_pack, ) -from packs.datatrees import _data_directory_members, core_data_trees, pack_markers -from packs.emulatorpack import _system_display_name +from packs.datatrees import data_directory_members, core_data_trees, pack_markers +from packs.emulatorpack import system_display_name from packs.extras import ( ExtraResolver, - _collect_emulator_extras, - _detect_extras_prefix, + collect_emulator_extras, + detect_extras_prefix, extra_full_destination, extra_region_key, extras_for_systems as _extras_for_systems, platform_region_groups, undeclared_report, ) -from packs.naming import _name_part, _narrowings, _platform_pack_name, _platform_pack_stem -from packs.paths import _flat, save_layout -from packs.readme import _build_agnostic_rename_readme, _build_readme, save_place +from packs.naming import file_name_part, pack_narrowings, platform_pack_name, platform_pack_stem +from packs.paths import flat_arcname, save_layout +from packs.readme import build_agnostic_rename_readme, build_readme, save_place from resolve import packfiles as packresolve, regions as resolve_regions, slot as slot_mod from resolve.contentlayout import TARGET_KEY from resolve.cores import platform_scope_systems, system_scope_error @@ -59,8 +59,8 @@ from resolve.packfiles import ( resolve_file, ) from resolve.validation import ( - _build_validation_index, - _parse_validation, + build_validation_index, + parse_validation, agnostic_substitute, baseline_verdict, destination_owners, @@ -78,7 +78,7 @@ def _case_twin_pairs( ) -> list[tuple[str, str]]: """Each spelling left out, with the spelling the pack holds.""" held = { - _flat(dest, base_dest, flatten).lower(): _flat(dest, base_dest, flatten) + flat_arcname(dest, base_dest, flatten).lower(): flat_arcname(dest, base_dest, flatten) for dest in seen_destinations } return sorted({(twin, held[twin.lower()]) for twin in twins if twin.lower() in held}) @@ -201,7 +201,7 @@ def _select_variants( slot_undecidable: list[str] = [] if one_per_slot: - slot_drops, slot_undecidable = _slot_drops( + slot_drops, slot_undecidable = one_per_slot_drops( config, emu_profiles, target_cores, region_groups, region_drops, held ) region_drops = region_drops | slot_drops @@ -214,7 +214,7 @@ def _select_variants( return region_drops, region_fallbacks, slot_undecidable -def _slot_drops( +def one_per_slot_drops( config: dict, emu_profiles: dict | None, target_cores: set[str] | None, @@ -247,7 +247,7 @@ def _matches_an_alternative(fe: dict, local_path: str, profiles: dict) -> bool: return False # A sibling the code takes without a check (Raze's "BLOOD: Unknown # Version") accepts whatever copy fills the slot. - if any(not _parse_validation(entry.get("validation")) for entry in siblings): + if any(not parse_validation(entry.get("validation")) for entry in siblings): return True actual = compute_hashes(local_path, frozenset({"sha1", "md5", "crc32"})) for entry in siblings: @@ -408,13 +408,13 @@ def _plan_platform_pack( if cut is not None: config, emu_profiles = cut.config, cut.profiles - narrowings = _narrowings( + narrowings = pack_narrowings( opts.source, opts.regions, opts.target_name, opts.one_per_slot, opts.required_only, no_game_data=opts.no_game_data, ) zip_path = os.path.join( output_dir, - _platform_pack_name( + platform_pack_name( platform_name, platforms_dir, narrowings, opts.system_filter, opts.pack_name ), ) @@ -432,7 +432,7 @@ def _plan_platform_pack( name: emu_profiles[name] for name in resolve_platform_cores(config, emu_profiles) } - validation_index = _build_validation_index(platform_profiles) + validation_index = build_validation_index(platform_profiles) validation_owners = destination_owners(platform_profiles) slot_overrides = slots.pack_overrides( config, emu_profiles or {}, db, zip_contents, opts.data_registry, @@ -515,7 +515,7 @@ class _PlatformPackBuild: verdict: Callable[[dict, str | None, str], tuple[str, str | None]] judge: Callable[[dict, str | None, str], tuple[str | None, str | None]] resolve_extra: Callable[[dict, str], tuple[str | None, str, str]] - placed: _Placed = field(init=False) + placed: Placed = field(init=False) total_files: int = 0 core_count: int = 0 save_count: int = 0 @@ -532,10 +532,10 @@ class _PlatformPackBuild: case_twins: list[str] = field(default_factory=list) def __post_init__(self) -> None: - self.placed = _Placed(self.plan.case_insensitive) + self.placed = Placed(self.plan.case_insensitive) def _flat(self, path: str) -> str: - return _flat(path, self.plan.base_dest, self.plan.opts.flatten) + return flat_arcname(path, self.plan.base_dest, self.plan.opts.flatten) def run(self) -> None: if self.plan.opts.source != "truth": @@ -642,7 +642,7 @@ class _PlatformPackBuild: instr_path = ( f"{base_dest}/{instr_name}" if base_dest else instr_name ) - _write_generated_member( + write_generated_member( self.zf, self._flat(instr_path), f"File needed: {file_entry['name']}\n\n{instructions}\n", @@ -664,9 +664,9 @@ class _PlatformPackBuild: if self.plan.opts.record is None and download_external(file_entry, tmp_path): extract = file_entry.get("extract", False) if extract and tmp_path.endswith(".zip"): - _extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf) + extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf) else: - _add_pack_member(self.zf, tmp_path, self._flat(full_dest)) + add_pack_member(self.zf, tmp_path, self._flat(full_dest)) self.file_status.setdefault(full_dest, "ok") self.total_files += 1 else: @@ -700,11 +700,11 @@ class _PlatformPackBuild: if entry.get("path", "").startswith(agnostic_path) and entry.get("name", "") and entry.get("name", "") != original_name ] - readme_text = _build_agnostic_rename_readme(dest_name, original_name, alt_names) + readme_text = build_agnostic_rename_readme(dest_name, original_name, alt_names) readme_name = f"RENAMED_{dest_name}.txt" readme_full = f"{plan.base_dest}/{readme_name}" if plan.base_dest else readme_name if readme_full not in self.placed.destinations: - _write_generated_member(self.zf, self._flat(readme_full), readme_text) + write_generated_member(self.zf, self._flat(readme_full), readme_text) self.placed.destinations.add(readme_full) return local_path @@ -766,7 +766,7 @@ class _PlatformPackBuild: if full_dest not in self.placed.destinations: self.case_twins.append(self._flat(full_dest)) return - if within is not None and not _same_bytes(local_path, within.get(self._flat(full_dest))): + if within is not None and not same_bytes(local_path, within.get(self._flat(full_dest))): # The full pack holds another system's file here. return if self.file_status.get(full_dest) == "excluded": @@ -777,11 +777,11 @@ class _PlatformPackBuild: extract = file_entry.get("extract", False) flat_dest = self._flat(full_dest) if extract and local_path.endswith(".zip"): - _extract_zip_to_archive(local_path, flat_dest, self.zf) + extract_zip_to_archive(local_path, flat_dest, self.zf) elif local_path.endswith(".zip"): - _add_zip_to_pack(local_path, flat_dest, self.zf, file_entry) + add_zip_to_pack(local_path, flat_dest, self.zf, file_entry) else: - _add_pack_member(self.zf, local_path, flat_dest) + add_pack_member(self.zf, local_path, flat_dest) self.total_files += 1 def _region_dropped(self, fe: dict) -> bool: @@ -803,14 +803,14 @@ class _PlatformPackBuild: # The systems asked for, with what their cores need: the split # packs get exactly this, and a full pack of one system had none. return _extras_for_systems( - _collect_emulator_extras( + collect_emulator_extras( plan.config, opts.emulators_dir, plan.db, set(), plan.base_dest, plan.emu_profiles, target_cores=opts.target_cores, include_all=(opts.source == "truth"), undeclared=plan.undeclared, ), opts.system_filter, ) - return _collect_emulator_extras( + return collect_emulator_extras( plan.config, opts.emulators_dir, plan.db, @@ -842,13 +842,13 @@ class _PlatformPackBuild: # pack is extracted into the BIOS folder and cannot reach # them, the installer places these files. return - # Core extras: _collect_emulator_extras already adjusted + # Core extras: collect_emulator_extras already adjusted # destinations for slug-based platforms. Apply the effective # prefix (base_dest, or inferred from YAML when base_dest is # empty, as RetroDECK infers "bios"). A file read below the save # directory goes to the pack's save folder instead. full_dest = extra_full_destination( - fe, _detect_extras_prefix(plan.config, plan.base_dest) + fe, detect_extras_prefix(plan.config, plan.base_dest) ) if not full_dest: return @@ -872,12 +872,12 @@ class _PlatformPackBuild: flat_dest = self._flat(full_dest) within = plan.opts.within - if within is not None and not _same_bytes(local_path, within.get(flat_dest)): + if within is not None and not same_bytes(local_path, within.get(flat_dest)): return if local_path.endswith(".zip"): - _add_zip_to_pack(local_path, flat_dest, self.zf, fe) + add_zip_to_pack(local_path, flat_dest, self.zf, fe) else: - _add_pack_member(self.zf, local_path, flat_dest) + add_pack_member(self.zf, local_path, flat_dest) if self.file_status.get(full_dest) in ("missing", "excluded"): self._core_fills_declaration(fe, full_dest) self.placed.take(full_dest) @@ -952,13 +952,13 @@ class _PlatformPackBuild: required_only = plan.opts.required_only seen_parents = self.placed.parents added = 0 - for src, full in _data_directory_members( + for src, full in data_directory_members( pack_systems, plan.opts.data_registry, plan.platform_name, plan.base_dest, self.placed.fold, self.placed.destinations, self.placed.lower, seen_parents, required_only=required_only, core_trees=core_trees, ): - _add_pack_member(self.zf, src, self._flat(full)) + add_pack_member(self.zf, src, self._flat(full)) if isinstance(self.zf, PackRecord): self.zf.trees.append(self._flat(full)) added += 1 @@ -970,14 +970,14 @@ class _PlatformPackBuild: # them, as the manifest's case_variants are (Mesen-CE's bios.col # beside the declared BIOS.col). plan, opts = self.plan, self.plan.opts - unfolded = _collect_emulator_extras( + unfolded = collect_emulator_extras( {**plan.config, "case_insensitive_fs": False}, opts.emulators_dir, plan.db, set(), plan.base_dest, plan.emu_profiles, target_cores=opts.target_cores, include_all=(opts.source == "truth"), ) if opts.system_filter: unfolded = _extras_for_systems(unfolded, opts.system_filter) - prefix = _detect_extras_prefix(plan.config, plan.base_dest) + prefix = detect_extras_prefix(plan.config, plan.base_dest) unfolded_spares = self._spares(unfolded) for fe in unfolded: if opts.required_only and (fe.get("required") is False or id(fe) in unfolded_spares): @@ -1004,7 +1004,7 @@ class _PlatformPackBuild: if keeps_case and opts.source != "platform" and opts.precomputed_extras is None: self._unfolded_twins() save_count = self.save_count - readme_text = _build_readme( + readme_text = build_readme( plan.platform_name, plan.platform_display, plan.base_dest, self.total_files, len(plan.pack_systems), source=opts.source, @@ -1033,9 +1033,9 @@ class _PlatformPackBuild: if keeps_case else [] ), ) - _write_generated_member(self.zf, "README.txt", readme_text) + write_generated_member(self.zf, "README.txt", readme_text) for marker in pack_markers(plan.platform_name, opts.target_name, plan.platforms_dir): - _write_generated_member( + write_generated_member( self.zf, self._flat(f"{plan.base_dest}/{marker}" if plan.base_dest else marker), "", @@ -1136,7 +1136,7 @@ def generate_pack( with ( contextlib.nullcontext(opts.record) if opts.record is not None - else _writing_pack(plan.zip_path) + else writing_pack(plan.zip_path) ) as zf: build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra) build.run() @@ -1181,7 +1181,7 @@ def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict if source == "platform": all_extras = [] elif emu_profiles: - all_extras = _collect_emulator_extras( + all_extras = collect_emulator_extras( cut.config if cut else config, narrowing["emulators_dir"], db, set(), base_dest, cut.profiles if cut else emu_profiles, target_cores=target_cores, include_all=(source == "truth"), @@ -1229,7 +1229,7 @@ def generate_split_packs( # differently narrowed runs write into one another. split_tags = "".join( tag - for tag, _label in _narrowings( + for tag, _label in pack_narrowings( narrowing["source"], narrowing["regions"], narrowing["target_name"], narrowing["one_per_slot"], narrowing["required_only"], no_game_data=narrowing["no_game_data"], @@ -1244,7 +1244,7 @@ def generate_split_packs( # Named by the stem the full pack reads: assembled here by hand, a '/' in # a version nested the directory where the check never looked for it. part_prefix = ( - f"{_platform_pack_stem([platform_name], platform_name, platforms_dir)}{split_tags}" + f"{platform_pack_stem([platform_name], platform_name, platforms_dir)}{split_tags}" ) split_dir = os.path.join(output_dir, f"{part_prefix}{group_tag}_Split") if records is None: @@ -1278,14 +1278,14 @@ def generate_split_packs( if group_by == "manufacturer": groups = _group_systems_by_manufacturer(systems, db, bios_dir) else: - groups = {_system_display_name(sid): [sid] for sid in systems} + groups = {system_display_name(sid): [sid] for sid in systems} all_extras = _split_extras(config, db, narrowing) results = [] for group_name, group_system_ids in sorted(groups.items()): group_extras = _extras_for_systems(all_extras, group_system_ids) zip_path = part( - f"{part_prefix}_{_name_part(group_name, '_')}_BIOS_Pack.zip", + f"{part_prefix}_{file_name_part(group_name, '_')}_BIOS_Pack.zip", {"system_filter": group_system_ids, "precomputed_extras": group_extras}, ) if zip_path: diff --git a/scripts/packs/readme.py b/scripts/packs/readme.py index 2943232cf..5b565bd39 100644 --- a/scripts/packs/readme.py +++ b/scripts/packs/readme.py @@ -214,7 +214,7 @@ class ReadmeOptions(TypedDict, total=False): case_twins: list[tuple[str, str]] | None -def _build_readme( +def build_readme( platform_name: str, platform_display: str, base_dest: str, @@ -235,7 +235,7 @@ def _build_readme( where names keep their case (EmuDeck and RetroArch on Linux), where the core asking for the other spelling finds nothing. """ - reject_unknown("_build_readme", options, ReadmeOptions.__optional_keys__) + reject_unknown("build_readme", options, ReadmeOptions.__optional_keys__) regions = options.get("regions") launch_folders = options.get("launch_folders", 0) sep = "=" * 50 @@ -366,7 +366,7 @@ def _region_info(regions: list[str] | None, fallback_systems: list[str] | None) " Only the best-matching BIOS was kept for each system.\n" ) if fallback_systems: - listed = "\n".join(f" {_group_label(s)}" for s in fallback_systems) + listed = "\n".join(f" {group_label(s)}" for s in fallback_systems) region_info += ( "\n These systems have no BIOS in those regions, so every\n" " BIOS file for them was kept:\n" @@ -426,7 +426,7 @@ def _credits(contributors: list[dict] | None) -> str: return credits + "\n" -def _build_agnostic_rename_readme( +def build_agnostic_rename_readme( destination: str, original: str, alternatives: list[str], @@ -445,7 +445,7 @@ def _build_agnostic_rename_readme( return "\n".join(lines) + "\n" -def _group_label(group_id: str) -> str: +def group_label(group_id: str) -> str: """A region group as a reader names it: the system, or one core's slot.""" emulator, kind, rest = (group_id.split(":", 2) + ["", ""])[:3] if kind == "variant" and rest: diff --git a/scripts/packs/report.py b/scripts/packs/report.py index 82eb3a2d2..97f13df76 100644 --- a/scripts/packs/report.py +++ b/scripts/packs/report.py @@ -55,7 +55,7 @@ def _print_ground_truth(gt: list[dict], verbose: bool) -> None: print(f" {_format_ground_truth_aggregate(gt)}") -def _discrepancy_keys(details: list[dict]) -> set[str]: +def discrepancy_keys(details: list[dict]) -> set[str]: """The DISCREPANCY lines _print_detail_entries prints for these details. A file already reported MISSING or UNTESTED on its own ground is not @@ -76,7 +76,7 @@ def _discrepancy_keys(details: list[dict]) -> set[str]: # A platform entry that is not firmware, as the report names it. -_NOT_FIRMWARE = { +NOT_FIRMWARE = { "game_data": "game data", "unread": "no core the platform runs opens it", } @@ -149,7 +149,7 @@ def _print_missing_details(details: list[dict], seen: set[str], verbose: bool) - key = f"{d['system']}/{d['name']}" if key in seen: continue - label = _NOT_FIRMWARE.get(d.get("category", BIOS)) + label = NOT_FIRMWARE.get(d.get("category", BIOS)) if label: # Counted on their own line, named on request. if verbose: @@ -228,7 +228,7 @@ def _print_undeclared_entry( print(f" validates {'+'.join(checks)}") -def _split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], list[dict]]: +def split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], list[dict]]: """Game data, firmware the pack places, firmware it holds but cannot place. Everything that is not game data is firmware the core loads, archives @@ -242,7 +242,7 @@ def _split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], l return game_data, placed, unplaced -def _core_required_missing(bios_files: list[dict]) -> list[dict]: +def core_required_missing(bios_files: list[dict]) -> list[dict]: """Core files a core cannot run without, absent from the collection. A file bundled with the emulator (DaedalusX64's n64.psh, the shader @@ -287,7 +287,7 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None: if not undeclared and not (packed and any(packed.values())): return - game_data, bios_files, unplaced = _split_undeclared(undeclared) + game_data, bios_files, unplaced = split_undeclared(undeclared) # A file installed with its emulator is never collected, firmware or # game data, required or not: cross_reference counts it apart. The @@ -296,7 +296,7 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None: bundled = [u for u in undeclared if not u["in_repo"] and u.get("bundled")] game_data = [u for u in game_data if u["in_repo"] or not u.get("bundled")] - req_not_in_repo = _core_required_missing(bios_files) + req_not_in_repo = core_required_missing(bios_files) req_hle_not_in_repo = [ u for u in bios_files @@ -460,15 +460,15 @@ def _print_platform_notices(result: dict, verbose: bool) -> None: print(f" {line}") fallbacks = result.get("region_fallbacks") or [] if fallbacks: - from packs.readme import _group_label + from packs.readme import group_label print(f" No BIOS for the requested regions, all kept ({len(fallbacks)}): " - + ", ".join(_group_label(g) for g in fallbacks)) + + ", ".join(group_label(g) for g in fallbacks)) not_firmware = result.get("missing_not_firmware") or {} if not_firmware: counts = ", ".join( - f"{len(dests)} {_NOT_FIRMWARE[category]}" + f"{len(dests)} {NOT_FIRMWARE[category]}" for category, dests in not_firmware.items() ) listed = "" if verbose else " (--verbose lists them)" diff --git a/scripts/packs/slots.py b/scripts/packs/slots.py index 38a4eae06..24ed1645d 100644 --- a/scripts/packs/slots.py +++ b/scripts/packs/slots.py @@ -10,7 +10,7 @@ from core.hashing import parse_md5_list from model.profiles import entry_system_ids from resolve import nativemode from resolve.archives import archive_entry, holds_required_members -from resolve.collisions import _accepted_by_all, _content_sha1, _lists_hashes, _normalize +from resolve.collisions import accepted_by_all, content_sha1, lists_hashes, comparable_destination from resolve.cores import resolve_platform_cores from resolve.layout import system_dir_path from resolve.localfile import resolution_is_hash_exact, resolve_local_file @@ -374,7 +374,7 @@ def _slot_claims( for claim in platform_claims( config, db, base_dest, zip_contents, data_dir_registry ): - key = _normalize(claim.destination, fold) + key = comparable_destination(claim.destination, fold) held = by_dest.get(key) if held is not None and id(held.entry) in shipped: continue @@ -404,7 +404,7 @@ def _slot_claims( profiles, db, base_dest, standalone_cores, zip_contents, data_dir_registry, config=config, ): - key = _normalize(claim.destination, fold) + key = comparable_destination(claim.destination, fold) platform = by_dest.get(key) if platform is None or not claim.is_proven: continue @@ -619,25 +619,25 @@ def _satisfies(profile: Claim, platform: Claim, db: dict) -> bool: # Two paths can hold one content: AmberELEC's bluemsx declarations # resolve into the data/bluemsx cache, the profile's into bios/. if profile.local_path and platform.local_path: - shipped = _content_sha1(platform.local_path, db) - if shipped is not None and shipped == _content_sha1(profile.local_path, db): + shipped = content_sha1(platform.local_path, db) + if shipped is not None and shipped == content_sha1(profile.local_path, db): return True members = profile.entry.get("members") if members and platform.local_path: return holds_required_members(platform.local_path, members) if ( profile.local_path - and _lists_hashes(platform.entry) - and _accepted_by_all(profile.local_path, [platform.entry], db) + and lists_hashes(platform.entry) + and accepted_by_all(profile.local_path, [platform.entry], db) ): return True if platform.local_path and any( - _lists_hashes(label) and _accepted_by_all(platform.local_path, [label], db) + lists_hashes(label) and accepted_by_all(platform.local_path, [label], db) for label in profile.accepts ): return True return bool( platform.local_path - and _lists_hashes(profile.entry) - and _accepted_by_all(platform.local_path, [profile.entry], db) + and lists_hashes(profile.entry) + and accepted_by_all(platform.local_path, [profile.entry], db) ) diff --git a/scripts/packs/standalone.py b/scripts/packs/standalone.py index 295b0fcb9..f553a92fc 100644 --- a/scripts/packs/standalone.py +++ b/scripts/packs/standalone.py @@ -10,7 +10,7 @@ from pathlib import PurePosixPath from core.paths import REPO_ROOT from packs.archive import PackRecord from packs.emulatorpack import generate_emulator_pack -from packs.manifestentry import _manifest_entry +from packs.manifestentry import manifest_entry def _placed_copies(copies: list[dict], dests: list[str]) -> list[dict]: @@ -176,7 +176,7 @@ def _profile_copies( return copies -def _standalone_copies( +def standalone_copies( declared: list[dict], profiles: dict[str, dict], manifest_files: list[dict], ) -> list[dict]: """A manifest's standalone copies: the registry's, placed where this @@ -193,7 +193,7 @@ def _standalone_copies( STANDALONE_DIR = "standalone" -def _standalone_layouts( +def standalone_layouts( profiles: dict[str, dict], emulators_dir: str, db: dict, @@ -232,7 +232,7 @@ def _standalone_layouts( ) items: list = [] for member in record.files: - entry, _size = _manifest_entry( + entry, _size = manifest_entry( record.sources.get(member), member, [name], db, repo_root, {} ) if entry is None: diff --git a/scripts/packs/verdicts.py b/scripts/packs/verdicts.py index 2401d1862..edc664e38 100644 --- a/scripts/packs/verdicts.py +++ b/scripts/packs/verdicts.py @@ -40,8 +40,8 @@ class Severity: OK = "ok" # file verified -_STATUS_ORDER = {Status.OK: 0, Status.UNTESTED: 1, Status.MISSING: 2} -_SEVERITY_ORDER = { +STATUS_ORDER = {Status.OK: 0, Status.UNTESTED: 1, Status.MISSING: 2} +SEVERITY_ORDER = { Severity.OK: 0, Severity.INFO: 1, Severity.WARNING: 2, @@ -227,7 +227,7 @@ def verify_entry_sha1( # Severity mapping per platform -def _emulator_severity(status: str, required: bool, hle_fallback: bool) -> str: +def emulator_severity(status: str, required: bool, hle_fallback: bool) -> str: """Severity when the emulator's own code is the check. A file present but refused by the core's validation, or a different dump @@ -274,7 +274,7 @@ def compute_severity( return Severity.OK -def _storage_verdict(file_entry: dict, emulator_pack: bool) -> dict | None: +def storage_verdict(file_entry: dict, emulator_pack: bool) -> dict | None: """The result a storage tier fixes before any lookup, as the builder sees it. A user_provided entry is never taken from the collection: a platform pack diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 899160999..0739ff297 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -458,7 +458,7 @@ def _tree_members( from packs import datatrees from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packs.paths import _flat + from packs.paths import flat_arcname config = load_platform_config(platform, platforms_dir) base_dest = config.get("base_destination", "") @@ -468,12 +468,12 @@ def _tree_members( ) members: dict[str, int] = {} with contextlib.redirect_stdout(io.StringIO()): - for src, full in datatrees._data_directory_members( + for src, full in datatrees.data_directory_members( config.get("systems", {}), registry, platform, base_dest, False, set(), set(), set(), core_trees=core_trees, ): - members[_flat(full, base_dest, True)] = os.path.getsize(src) + members[flat_arcname(full, base_dest, True)] = os.path.getsize(src) return members @@ -588,7 +588,7 @@ def check_emulator_packs( profiles_for_systems, select_emulator_profiles, ) - from model.systems import _norm_system_id + from model.systems import norm_system_id from core.ziptools import build_zip_contents_index from model.database import load_database @@ -599,7 +599,7 @@ def check_emulator_packs( def compare(names: list[str], standalone: bool, label: str, **narrowing: object) -> bool: record = archive.PackRecord() - was_offline = packresolve._OFFLINE + was_offline = packresolve.OFFLINE # The pack is built offline: verify counts a release asset the cache # lacks the same way, missing, as the narrowed-pack step does. packresolve.set_offline(True) @@ -643,7 +643,7 @@ def check_emulator_packs( # rule that only goes wrong when two profiles share a path (the bluemsx # tree beside msx-emu's files) never meets in a one-profile pack. systems = sorted({ - _norm_system_id(str(sid)) + norm_system_id(str(sid)) for profile in profiles.values() if profile.get("type") not in ("launcher", "alias") and profile.get("role") != "test" for sid in profile.get("systems") or [] @@ -668,7 +668,7 @@ def check_emulator_packs( return all_ok and systems_ok -# How each _narrowings() dimension of a platform pack is compared by +# How each pack_narrowings() dimension of a platform pack is compared by # check_narrowed_packs, or why it is not. A test reads the builder's # signature against these two tables, so a new narrowing fails it until it # is compared or a reason is written here. Emulator packs have their own @@ -772,7 +772,7 @@ def check_narrowed_packs( list_registered_platforms(platforms_dir), platforms_dir, ) - was_offline = packresolve._OFFLINE + was_offline = packresolve.OFFLINE packresolve.set_offline(True) all_ok = True compared = 0 @@ -881,7 +881,7 @@ def check_split_packs( list_registered_platforms(platforms_dir), platforms_dir, ) - was_offline = packresolve._OFFLINE + was_offline = packresolve.OFFLINE packresolve.set_offline(True) all_ok = True try: @@ -900,7 +900,7 @@ def check_split_packs( packs_platformpack.generate_split_packs( platform, platforms_dir, db, "bios", "", records=parts, **args, ) - lines = split_differences(full, parts, archive._same_bytes) + lines = split_differences(full, parts, archive.same_bytes) if lines: all_ok = False print(f" {platform} --split: {len(lines)} differences") diff --git a/scripts/probes/packprobe.py b/scripts/probes/packprobe.py index ba201c8ff..7aafe0693 100644 --- a/scripts/probes/packprobe.py +++ b/scripts/probes/packprobe.py @@ -25,7 +25,7 @@ from core.statefile import now_iso from model import measurements as mr from model.platforms import load_platform_config from model.profiles import load_emulator_profiles -from model.systems import _norm_system_id +from model.systems import norm_system_id from model.targets import load_target_config from probes.content import Content, load_content, load_file, verify_identity from probes.cores import BUILDBOT, safe_extract_so @@ -72,8 +72,8 @@ class CoreChoice: def platform_system(config: dict, system: str) -> str | None: """The platform's own id of a system, compared on the normalised id.""" - wanted = _norm_system_id(system) - matches = sorted(s for s in config.get("systems") or {} if _norm_system_id(s) == wanted) + wanted = norm_system_id(system) + matches = sorted(s for s in config.get("systems") or {} if norm_system_id(s) == wanted) return matches[0] if matches else None @@ -105,11 +105,11 @@ def so_names(name: str, profile: dict, buildbot: set[str], target: set[str] | No def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot: set[str], target: set[str] | None) -> list[CoreChoice]: - wanted = _norm_system_id(system) + wanted = norm_system_id(system) out: list[CoreChoice] = [] for name in sorted(resolve_platform_cores(config, profiles, target)): profile = profiles[name] - if wanted not in {_norm_system_id(s) for s in profile.get("systems") or ()}: + if wanted not in {norm_system_id(s) for s in profile.get("systems") or ()}: continue if not libretro_build_runs(name, profile, config): continue diff --git a/scripts/profile_sync.py b/scripts/profile_sync.py index 950b78bb3..db43fe67a 100644 --- a/scripts/profile_sync.py +++ b/scripts/profile_sync.py @@ -22,15 +22,15 @@ sys.path.insert(0, os.path.dirname(__file__)) from core import upstream from profiling import version_basis -from model.systems import _norm_system_id, system_index +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 profiling.bump import DEFAULT_CACHE, write_version from profiling.realign import realign_prose from profiling.reports import ProfileReport -from profiling.run import _WRITTEN, _emit, _read_one -from profiling.triage import PROGRESS_SECONDS, _Progress, _interrupted +from profiling.run import WRITTEN_PROFILES, emit_reports, read_one_profile +from profiling.triage import PROGRESS_SECONDS, Progress, print_interrupted from profiling.yamledit import YamlWriteError ANON_QUOTA = 60 @@ -289,9 +289,9 @@ def project_base() -> str: is HEAD, and --changed --strict found nothing and passed while the PR's CI then failed. validate_pr.py resolves the same line the same way. """ - from core.gitclone import _git_lines as git_lines, _project_main_line + from core.gitclone import git_lines as git_lines, project_main_line - line = _project_main_line() + line = project_main_line() if line: return line for remote in ("upstream", "origin"): @@ -328,13 +328,13 @@ def select_profiles(profiles: dict, args: argparse.Namespace) -> dict: # --system matches as verify.py --list-systems lists and --system selects: # by normalized id, so `saturn` reaches the profiles declaring sega-saturn. - wanted_system = _norm_system_id(args.system) if args.system else None + wanted_system = norm_system_id(args.system) if args.system else None selected = {} for name, profile in sorted(profiles.items()): if profile.get("type") == "alias" or profile.get("role") == "test": continue if wanted_system and wanted_system not in { - _norm_system_id(str(s)) for s in profile.get("systems") or [] + norm_system_id(str(s)) for s in profile.get("systems") or [] }: continue if args.type_ and profile.get("type") != args.type_: @@ -589,16 +589,16 @@ def main() -> None: f"{PROGRESS_SECONDS} s. --offline answers from the cache alone.", file=sys.stderr, flush=True, ) - progress = _Progress(len(selected), "read", quiet) + progress = Progress(len(selected), "read", quiet) complete = True try: for name, profile in selected.items(): progress.step(len(reports), name) - _read_one(args, name, profile, reports, failed, writes) + read_one_profile(args, name, profile, reports, failed, writes) except KeyboardInterrupt: # What was read is still worth printing: a ranking of 200 profiles # beats none after 15 minutes. - _interrupted(len(reports), len(selected), "the output covers those read") + print_interrupted(len(reports), len(selected), "the output covers those read") complete = False # --changed-only narrows every output, not the text report alone: the @@ -607,7 +607,7 @@ def main() -> None: report for report in reports if not args.changed_only or report.needs_review() or report.name in failed ] - complete = _emit(args, selected, reports, shown) is not False and complete + complete = emit_reports(args, selected, reports, shown) is not False and complete _refresh_source_paths(args) if not complete: raise SystemExit(130) @@ -631,7 +631,7 @@ def _run_realign(args: argparse.Namespace, selected: dict) -> None: ): print(f"{name}: {line}") if profile_path.read_bytes() != before: - _WRITTEN.add(name) + WRITTEN_PROFILES.add(name) except upstream.UpstreamError as exc: print(f"{name}: {exc}", file=sys.stderr) failed.add(name) @@ -651,16 +651,16 @@ def _refresh_source_paths(args: argparse.Namespace) -> None: --fetch by hand. A run that writes nothing, or makes no request, leaves it alone. """ - if not _WRITTEN or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"): + if not WRITTEN_PROFILES or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"): return - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from sitegen import sources from core.artifacts import write_if_changed # The run loaded the profiles before writing them, and the loader caches # by directory: read again, the record described the pins just replaced # (linapple, then ten profiles in one advance). - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False) held, unread = sources.build_source_paths( profiles, [sources.TREE_CACHE], fetch=True diff --git a/scripts/profiling/citations.py b/scripts/profiling/citations.py index 08d7a8911..bfaba0627 100644 --- a/scripts/profiling/citations.py +++ b/scripts/profiling/citations.py @@ -15,7 +15,7 @@ import yaml from core import upstream from core.hashing import parse_hash_list -from model.sourceref import RefPart, _prose_runs, ref_prose_text, ref_role, source_ref_values +from model.sourceref import RefPart, prose_runs, ref_prose_text, ref_role, source_ref_values from profiling.repos import declared_repositories @@ -155,7 +155,7 @@ def symlink_target(path: str, lines: list[str] | None) -> str | None: return None if resolved.startswith("..") or resolved == path else resolved -def _anchor_tokens(entry: dict) -> list[str]: +def anchor_tokens(entry: dict) -> list[str]: """Values worth searching for when a cited line misses its subject. Both the content values and the set name are searched, because profiles @@ -309,7 +309,7 @@ def comment_citations( continue comment = line[column + 1:].rstrip("\r\n") shift = column + 1 - for _, path_span, run_spans, parts, run, _ in _prose_runs(comment, known): + for _, path_span, run_spans, parts, run, _ in prose_runs(comment, known): citations.append(Citation( field=f"comment line {number + 1}", kind="prose", ref=run, line=number, @@ -346,7 +346,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation] holder=holder, key=key, label=label, )) if isinstance(value, str): - for line, path_span, spans, parts, run, joined_at in _prose_runs( + for line, path_span, spans, parts, run, joined_at in prose_runs( ref_prose_text(value), known ): citations.append(Citation( @@ -355,7 +355,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation] parts=parts, wrapped=bool(joined_at), joined_at=joined_at, )) continue - for line, path_span, spans, parts, run, joined_at in _prose_runs( + for line, path_span, spans, parts, run, joined_at in prose_runs( value, known ): citations.append(Citation( @@ -368,7 +368,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation] return citations -def _citation_key(ref: str) -> str: +def citation_key(ref: str) -> str: """A citation compared without the spacing the author chose. A recale rewrites the located tokens and leaves the sentence alone, so diff --git a/scripts/profiling/detection.py b/scripts/profiling/detection.py index 62113aae1..f7d2e270e 100644 --- a/scripts/profiling/detection.py +++ b/scripts/profiling/detection.py @@ -194,20 +194,20 @@ def tree_diff(result: CompareResult, ref_dirs: set[str]) -> list[str]: return lines -def _cited_paths(report: ProfileReport) -> list[str]: +def cited_paths(report: ProfileReport) -> list[str]: return sorted( {part.new_path or part.part.path for e in report.entries for part in e.parts} ) -def _detect( +def detect_upstream_changes( args: argparse.Namespace, profile: dict, report: ProfileReport, repo: upstream.Repo, ) -> None: names, hashes = declared_names(profile), declared_hashes(profile) new_files: list[dict] = [] new_hashes: list[dict] = [] - for path in _cited_paths(report): + for path in cited_paths(report): head_lines = upstream.fetch_file( repo, report.head, path, args.cache_dir, args.offline ) @@ -259,7 +259,7 @@ def _print_detection(report: ProfileReport) -> None: print(f" new {item['kind']}: {item['path']} {item['value']}") -def _print_extras( +def print_extras( args: argparse.Namespace, profile: dict, report: ProfileReport ) -> None: """Optional per-profile sections beyond the ref report. @@ -288,7 +288,7 @@ def _print_extras_from( repo: upstream.Repo, ) -> None: if args.full_diff: - for path in _cited_paths(report): + for path in cited_paths(report): if args.ref and args.ref not in path: continue pin_lines = ( @@ -312,6 +312,6 @@ def _print_extras_from( ) # The repository root is a directory like any other: dropping the # empty dirname would turn the filter off and list the whole tree. - ref_dirs = {posixpath.dirname(p) for p in _cited_paths(report)} + ref_dirs = {posixpath.dirname(p) for p in cited_paths(report)} for line in tree_diff(comparison, ref_dirs): print(f" {line}") diff --git a/scripts/profiling/proseedit.py b/scripts/profiling/proseedit.py index 13983eeec..b17bc390d 100644 --- a/scripts/profiling/proseedit.py +++ b/scripts/profiling/proseedit.py @@ -15,7 +15,7 @@ from profiling.citations import Citation _RANGE_TOKEN_RE = re.compile(r"\d+(?:-\d+)?") -def _run_after_moves( +def run_after_moves( parts: Sequence[RefPart], moves: dict[int, tuple[int, int, str | None]], run: str = "", @@ -108,7 +108,7 @@ def _scalar(holder: object, key: object) -> object: raise TypeError(f"no scalar under {key!r} in a {type(holder).__name__}") -def _set_scalar(holder: object, key: object, value: str) -> None: +def set_scalar(holder: object, key: object, value: str) -> None: """Replace the value a citation's holder keeps under its key.""" if isinstance(holder, dict): holder[key] = value @@ -275,7 +275,7 @@ def _edit_scalar_run( edits.applied.append(f"{citation.field}: {citation.ref} -> {recaled}") -def _apply_prose_edits( +def apply_prose_edits( text: str, jobs: list[tuple[Citation, dict]], document: object = None ) -> tuple[str, list[str], list[str]]: """Rewrite prose citation tokens in place, nothing else. @@ -297,7 +297,7 @@ def _apply_prose_edits( for citation, moves in jobs: replacements = _prose_replacements(citation, moves) - recaled = _run_after_moves(citation.parts, moves, citation.ref) + recaled = run_after_moves(citation.parts, moves, citation.ref) if citation.in_comment: _edit_comment_run(edits, citation, replacements, recaled) else: @@ -311,7 +311,7 @@ def _apply_prose_edits( value_lines = value.splitlines() for line_number, spans in by_line.items(): value_lines[line_number] = _replace_spans(value_lines[line_number], spans) - _set_scalar(holder, key, "\n".join(value_lines) + ( + set_scalar(holder, key, "\n".join(value_lines) + ( "\n" if value.endswith("\n") else "" )) return "\n".join(lines) + trailing, edits.applied, edits.left diff --git a/scripts/profiling/realign.py b/scripts/profiling/realign.py index 9b81f9a8e..91deba0bf 100644 --- a/scripts/profiling/realign.py +++ b/scripts/profiling/realign.py @@ -14,8 +14,8 @@ import yaml from core import upstream from model.sourceref import RefPart from profiling.anchoring import anchor_block -from profiling.citations import Citation, _citation_key, collect_citations, is_external_citation -from profiling.proseedit import _apply_prose_edits, _run_after_moves +from profiling.citations import Citation, citation_key, collect_citations, is_external_citation +from profiling.proseedit import apply_prose_edits, run_after_moves from profiling.repos import declared_repositories from profiling.yamledit import apply_edit @@ -383,7 +383,7 @@ class _ProseHistory: def _carried_by(past: dict) -> set[tuple[str, str]]: return { - (c.field, _citation_key(c.ref)) + (c.field, citation_key(c.ref)) for c in collect_citations(past) if c.kind == "prose" } @@ -510,18 +510,18 @@ def realign_prose( # one of its citations is corrected by hand, and dating the whole field # from that commit put idtech4a++'s untouched Game.java:69-72 under the # current pin, so the stale range was never offered again. - keys = [(c.field, _citation_key(c.ref)) for c in citations] + keys = [(c.field, citation_key(c.ref)) for c in citations] dated = _date_prose(path, document, keys, history) messages, jobs = _prose_jobs(document, citations, dated, declared, cache_dir, offline) if dry_run: messages.extend( f"would recale {citation.field}: {citation.ref} -> " - f"{_run_after_moves(citation.parts, moves, citation.ref)}" + f"{run_after_moves(citation.parts, moves, citation.ref)}" for citation, moves in jobs ) return messages - new_text, applied, left = _apply_prose_edits(text, jobs, document) + new_text, applied, left = apply_prose_edits(text, jobs, document) messages.extend(applied) messages.extend(f"left in place: {item}" for item in left) if applied: diff --git a/scripts/profiling/rebase.py b/scripts/profiling/rebase.py index a464d2b03..2fa3d3afa 100644 --- a/scripts/profiling/rebase.py +++ b/scripts/profiling/rebase.py @@ -10,9 +10,9 @@ import yaml from core import upstream from model.sourceref import ref_role, split_outside_parentheses, split_source_ref from profiling.anchoring import PartResult, REBASE_STATUSES, REVIEW_STATUSES -from profiling.citations import Citation, _citation_key, collect_citations -from profiling.proseedit import _apply_prose_edits, _run_after_moves, _set_scalar -from profiling.reports import EntryReport, ProfileReport, _original_part, _rendered_part +from profiling.citations import Citation, citation_key, collect_citations +from profiling.proseedit import apply_prose_edits, run_after_moves, set_scalar +from profiling.reports import EntryReport, ProfileReport, original_part, rendered_part from profiling.repos import declared_repositories from profiling.yamledit import YamlWriteError, apply_edit, find_field_line, replace_field_line @@ -107,7 +107,7 @@ def pin_blockers(report: ProfileReport, accept_changed: bool = False) -> list[st if not any( part.status in movable and part.start is not None - and _rendered_part(part) != _original_part(part) + and rendered_part(part) != original_part(part) for part in entry.parts ): continue @@ -156,7 +156,7 @@ def attribute_refs(path: Path, report: ProfileReport, profile: dict) -> list[str continue rendered = [] for part in entry.parts: - raw = part.part.raw or _original_part(part) + raw = part.part.raw or original_part(part) role, bare = ref_role(raw) written_path = bare.startswith(part.part.path) owner = role_of.get(part.repo or "", primary) if part.repo else primary @@ -185,7 +185,7 @@ def _moved_by_hand(entry: EntryReport, statuses: tuple[str, ...]) -> bool: return any( part.status in statuses and part.start is not None - and _rendered_part(part) != _original_part(part) + and rendered_part(part) != original_part(part) for part in entry.parts ) @@ -196,12 +196,12 @@ def _recaled_ref(entry: EntryReport, statuses: tuple[str, ...]) -> str | None: touched = False for part in entry.parts: if part.status in statuses and part.start is not None: - recaled = _rendered_part(part) - if recaled != _original_part(part): + recaled = rendered_part(part) + if recaled != original_part(part): touched = True rendered.append(recaled) else: - rendered.append(_original_part(part)) + rendered.append(original_part(part)) return ", ".join(rendered) if touched else None @@ -285,10 +285,10 @@ def rebase_refs( text, "source_ref", entry.source_ref, new_ref, cursor ) cursor = index + 1 - _set_scalar(citation.holder, citation.key, new_ref) + set_scalar(citation.holder, citation.key, new_ref) applied.append(f"{entry.source_ref} -> {new_ref}") - text, prose_applied, left = _apply_prose_edits(text, prose_jobs, document) + text, prose_applied, left = apply_prose_edits(text, prose_jobs, document) refused.extend(left) if refused: # A citation left on the pinned lines holds the pin, so writing the @@ -336,7 +336,7 @@ def _pending_refs( for part in entry.parts if part.status in movable and part.start is not None - and _rendered_part(part) != _original_part(part) + and rendered_part(part) != original_part(part) ) return pending @@ -348,7 +348,7 @@ def _pending_prose( pool: dict[tuple[str, str], int] = {} for citation in collect_citations(document, text): if citation.kind == "prose": - slot = (citation.field, _citation_key(citation.ref)) + slot = (citation.field, citation_key(citation.ref)) pool[slot] = pool.get(slot, 0) + 1 pending = 0 for entry in report.entries or []: @@ -361,12 +361,12 @@ def _pending_prose( if any(_part_moves(part, movable) for part in entry.parts): pending += 1 continue - rendered = _run_after_moves( + rendered = run_after_moves( [p.part for p in entry.parts], moves, entry.source_ref ) - if _citation_key(rendered) == _citation_key(entry.source_ref): + if citation_key(rendered) == citation_key(entry.source_ref): continue - slot = (entry.field, _citation_key(rendered)) + slot = (entry.field, citation_key(rendered)) if pool.get(slot, 0) > 0: pool[slot] -= 1 continue diff --git a/scripts/profiling/reports.py b/scripts/profiling/reports.py index 3a3e7ba49..d89db84ae 100644 --- a/scripts/profiling/reports.py +++ b/scripts/profiling/reports.py @@ -5,7 +5,7 @@ from __future__ import annotations from dataclasses import asdict, dataclass, field from core import upstream -from model.sourceref import _ANNOTATION_RE, _trim_prose +from model.sourceref import ANNOTATION_RE, trim_prose from profiling.anchoring import PartResult, REVIEW_STATUSES from profiling.versions import VersionReport @@ -142,20 +142,20 @@ def _render_span(path: str, start: int | None, end: int | None) -> str: return f"{path}:{start}" -def _original_part(part: PartResult) -> str: +def original_part(part: PartResult) -> str: """The part exactly as the profile writes it today.""" return part.part.raw or _render_span( part.part.path, part.part.start, part.part.end ) -def _rendered_part(part: PartResult) -> str: +def rendered_part(part: PartResult) -> str: """The part rewritten onto its new location, annotation preserved.""" span = _render_span(part.new_path or part.part.path, part.start, part.end) raw = part.part.raw if not raw: return span - located = _trim_prose(_ANNOTATION_RE.sub("", raw).strip()) + located = trim_prose(ANNOTATION_RE.sub("", raw).strip()) # `stella src/emucore/Cart.cxx:120` names the repository the lines are # in. The path was read without that word, and a recale wrote it back # without it: the attribution went with the old line numbers. @@ -182,7 +182,7 @@ def _part_line(part: PartResult) -> str: detail += f" ({part.reason})" if part.repo: detail += f" [{part.repo}]" - return f" {_original_part(part)} {detail}" + return f" {original_part(part)} {detail}" def _report_header(report: ProfileReport) -> list[str]: diff --git a/scripts/profiling/repos.py b/scripts/profiling/repos.py index d2d990ec5..314280ce7 100644 --- a/scripts/profiling/repos.py +++ b/scripts/profiling/repos.py @@ -407,6 +407,6 @@ def build_revision(profile: dict, platform: str) -> str | None: return None -def _on_own_revision(view: RepoView, tagged: dict[tuple[str, str], str]) -> bool: +def reads_own_revision(view: RepoView, tagged: dict[tuple[str, str], str]) -> bool: """Whether a view is read at its own revision: on HEAD, or on its tag.""" return view.pin == view.head or (view.repo.host, view.repo.slug) in tagged diff --git a/scripts/profiling/resolver.py b/scripts/profiling/resolver.py index 2a6ba422c..1f7e17196 100644 --- a/scripts/profiling/resolver.py +++ b/scripts/profiling/resolver.py @@ -29,7 +29,7 @@ from profiling.anchoring import ( ) from profiling.citations import ( Citation, - _anchor_tokens, + anchor_tokens, cites_another_version, collect_citations, entry_hashes, @@ -42,7 +42,7 @@ from profiling.reports import EntryReport, ProfileReport from profiling.repos import ( PIN, RepoView, - _on_own_revision, + reads_own_revision, build_revision, declared_repositories, detect_pinned_tag, @@ -187,7 +187,7 @@ def _gather_refs( for p in split_source_ref(citation.ref) ] refs.append(( - display, citation.ref, _anchor_tokens(entry), + display, citation.ref, anchor_tokens(entry), entry_hashes(entry), parts, citation, )) else: @@ -314,7 +314,7 @@ def _record_revisions( report.orphaned = [ f"{view.repo.slug}: pin {view.pin[:8]} is no ancestor of {view.head[:8]}" for view in views - if not _on_own_revision(view, tagged) + if not reads_own_revision(view, tagged) and upstream.compare( view.repo, view.pin, view.head, cache_dir, offline ).diverged @@ -397,7 +397,7 @@ class _Resolver: return next(iter(lent)) if len(lent) == 1 else "" def on_own_revision(self, view: RepoView) -> bool: - return _on_own_revision(view, self.tagged) + return reads_own_revision(view, self.tagged) def trees_in_order(self) -> Iterable[list[str] | None]: """Pin trees before HEAD trees, each read only when reached.""" diff --git a/scripts/profiling/run.py b/scripts/profiling/run.py index dd2d999ba..d9222d37a 100644 --- a/scripts/profiling/run.py +++ b/scripts/profiling/run.py @@ -13,7 +13,7 @@ import yaml from core import upstream from profiling.bump import bump_commit, pins_changed -from profiling.detection import _detect, _print_extras +from profiling.detection import detect_upstream_changes, print_extras from profiling.realign import realign_prose from profiling.rebase import attribute_refs, rebase_refs from profiling.reports import ( @@ -25,10 +25,10 @@ from profiling.reports import ( ) from profiling.repos import select_repo from profiling.resolver import build_report -from profiling.triage import _print_triage +from profiling.triage import print_triage from profiling.versions import ( - _newer_release, - _passed_release, + newer_release, + latest_passed_release, check_version, page_version, version_warning, @@ -135,7 +135,7 @@ def _promote( file=sys.stderr, ) return False - _WRITTEN.add(name) + WRITTEN_PROFILES.add(name) return True @@ -254,7 +254,7 @@ def _attach_detection( if repo is None: return try: - _detect(args, profile, report, repo) + detect_upstream_changes(args, profile, report, repo) except upstream.RateLimitError: raise except upstream.UpstreamError as exc: @@ -287,8 +287,8 @@ def _attach_version( relation = upstream.ancestry( repo, version.tag_commit, report.pin, args.cache_dir, args.offline ) - passed = _passed_release(args, repo, version, report.pin) - newer = None if passed or profile.get("pin_frozen") else _newer_release( + passed = latest_passed_release(args, repo, version, report.pin) + newer = None if passed or profile.get("pin_frozen") else newer_release( args, repo, version, report.pin ) except upstream.RateLimitError: @@ -303,7 +303,7 @@ def _attach_version( ) -def _read_one( +def read_one_profile( args: argparse.Namespace, name: str, profile: dict, @@ -344,7 +344,7 @@ def _read_one( # Profiles this run wrote. Their new pins name trees the site's record of # cited source paths does not hold yet. -_WRITTEN: set[str] = set() +WRITTEN_PROFILES: set[str] = set() def _build_full_report( @@ -402,7 +402,7 @@ def _build_full_report( return report -def _emit( +def emit_reports( args: argparse.Namespace, selected: dict, reports: list[ProfileReport], @@ -425,10 +425,10 @@ def _emit( print(url) return None if args.triage: - return _print_triage(args, selected, shown) + return print_triage(args, selected, shown) for report in shown: print(format_report(report, args.changed_only)) - _print_extras(args, selected[report.name], report) + print_extras(args, selected[report.name], report) print() if args.changed_only: _print_elided(reports, len(shown), frozenset(report.name for report in shown)) diff --git a/scripts/profiling/triage.py b/scripts/profiling/triage.py index 45a48e712..bfcdaf2ab 100644 --- a/scripts/profiling/triage.py +++ b/scripts/profiling/triage.py @@ -7,7 +7,7 @@ import sys import time from core import upstream -from profiling.detection import _cited_paths +from profiling.detection import cited_paths from profiling.reports import ProfileReport, triage_state from profiling.repos import select_repo from profiling.versions import VersionReport, check_version @@ -51,7 +51,7 @@ def drift_score( return score -class _Progress: +class Progress: """A stderr line every PROGRESS_SECONDS while a pass asks the forges.""" def __init__(self, total: int, doing: str, quiet: bool) -> None: @@ -65,25 +65,25 @@ class _Progress: self.last = now -def _interrupted(done: int, total: int, what: str) -> None: +def print_interrupted(done: int, total: int, what: str) -> None: print(f"interrupted after {done} of {total} profiles: {what}", file=sys.stderr, flush=True) -def _print_triage( +def print_triage( args: argparse.Namespace, selected: dict, reports: list[ProfileReport] ) -> bool: """Profiles ranked by drift, worst first. False when Ctrl-C cut the scoring short: the ranking then covers the profiles scored.""" ranked: list[tuple[int, ProfileReport, str]] = [] sampled = 0 - progress = _Progress(len(reports), "scored", args.offline or len(reports) < 2) + progress = Progress(len(reports), "scored", args.offline or len(reports) < 2) complete = True try: for done, report in enumerate(reports): progress.step(done, report.name) sampled += _score(args, selected, report, ranked) except KeyboardInterrupt: - _interrupted(len(ranked), len(reports), "the ranking covers those scored") + print_interrupted(len(ranked), len(reports), "the ranking covers those scored") complete = False if sampled: # One line for the run: a notice per profile buried the ranking @@ -117,7 +117,7 @@ def _score( sampled = False repo = select_repo(profile) if report.head and repo is not None: - paths = _cited_paths(report) + paths = cited_paths(report) try: version = check_version(profile, repo, args.cache_dir, args.offline) for path in paths[:TRIAGE_PATH_SAMPLE]: diff --git a/scripts/profiling/versions.py b/scripts/profiling/versions.py index 310b82032..bf352f0cb 100644 --- a/scripts/profiling/versions.py +++ b/scripts/profiling/versions.py @@ -149,7 +149,7 @@ def _later_number(candidate: str, declared: str) -> bool: return high[0] == low[0] and high > low -def _newer_release( +def newer_release( args: argparse.Namespace, repo: upstream.Repo, version: VersionReport | None, @@ -178,7 +178,7 @@ def _newer_release( return published -def _passed_release( +def latest_passed_release( args: argparse.Namespace, repo: upstream.Repo, version: VersionReport | None, diff --git a/scripts/release/record.py b/scripts/release/record.py index 3c3913626..78a4a25a2 100644 --- a/scripts/release/record.py +++ b/scripts/release/record.py @@ -32,7 +32,7 @@ def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]: platforms = list_release_pack_platforms(platforms_dir) owners: dict[str, list[str]] = {} - for platform, names in naming._expected_pack_names( + for platform, names in naming.expected_pack_names( platforms, platforms_dir, None, None ).items(): for name in names: diff --git a/scripts/resolve/archives.py b/scripts/resolve/archives.py index 382d335a9..622a3766e 100644 --- a/scripts/resolve/archives.py +++ b/scripts/resolve/archives.py @@ -136,7 +136,7 @@ def _member_held(member: dict, crcs: frozenset[str], names: frozenset[str]) -> b return named -def _holding_members(paths: list[str], members: list[dict]) -> list[str]: +def holding_members(paths: list[str], members: list[dict]) -> list[str]: """The same-named archives holding the most required members, then the most members. FBNeo reads neocd.bin and 000-lo.lo inside neocdz.zip. The primary copy, @@ -157,7 +157,7 @@ def _holding_members(paths: list[str], members: list[dict]) -> list[str]: return [path for path in paths if scores[path] == best] -def _covering_archives(paths: list[str]) -> list[str]: +def covering_archives(paths: list[str]) -> list[str]: """Same-named archives, those holding every ROM each other copy holds. Without a declared layout, a primary that is a superset of the other @@ -185,7 +185,7 @@ def _covering_archives(paths: list[str]) -> list[str]: _unreadable_archives: set[str] = set() -def _warn_unreadable_archive(path: str, exc: Exception) -> None: +def warn_unreadable_archive(path: str, exc: Exception) -> None: """Say once that an archive on disk cannot be read. Skipped in silence, a truncated ZIP came out as not_found or diff --git a/scripts/resolve/categories.py b/scripts/resolve/categories.py index 1f2516447..e72038c28 100644 --- a/scripts/resolve/categories.py +++ b/scripts/resolve/categories.py @@ -16,10 +16,10 @@ from dataclasses import dataclass, field from pathlib import Path -from model.systems import _norm_system_id +from model.systems import norm_system_id from resolve.cores import resolve_platform_cores, unresolved_platform_cores -from resolve.reconcile import HASH_FIELDS, NativeSystem, _hash_values -from resolve.launchers import _names as launcher_names +from resolve.reconcile import HASH_FIELDS, NativeSystem, hash_values +from resolve.launchers import record_names as launcher_names def _tails(path: str) -> list[str]: @@ -29,17 +29,17 @@ def _tails(path: str) -> list[str]: def _entry_hashes(entry: dict) -> set[str]: - values = {v for f in HASH_FIELDS for v in _hash_values(entry, f)} + values = {v for f in HASH_FIELDS for v in hash_values(entry, f)} for member in entry.get("contents") or []: if isinstance(member, dict): - values |= {v for f in HASH_FIELDS for v in _hash_values(member, f)} + values |= {v for f in HASH_FIELDS for v in hash_values(member, f)} return values def _declared_hashes(entry: dict) -> dict[str, set[str]]: """Hash field -> the values a platform entry declares, alt_md5 as md5.""" - found = {f: set(_hash_values(entry, f)) for f in HASH_FIELDS} - found["md5"] |= set(_hash_values(entry, "alt_md5")) + found = {f: set(hash_values(entry, f)) for f in HASH_FIELDS} + found["md5"] |= set(hash_values(entry, "alt_md5")) return {f: values for f, values in found.items() if values} @@ -53,7 +53,7 @@ def _contradicts(profile_entry: dict, declared: dict[str, set[str]]) -> bool: """True when both sides state the same kind of hash and no value agrees: the profile entry describes another dump under the same name.""" for field_name, values in declared.items(): - own = set(_hash_values(profile_entry, field_name)) + own = set(hash_values(profile_entry, field_name)) if own and not set(values) & set(own): return True return False @@ -138,7 +138,7 @@ class ReadEvidence: if names & self.names or (tails and tails[-1] in self.names): return "name" hashes = { - v for f in (*HASH_FIELDS, "alt_md5") for v in _hash_values(entry, f) + v for f in (*HASH_FIELDS, "alt_md5") for v in hash_values(entry, f) } if hashes & self.hashes: return "hash" @@ -196,7 +196,7 @@ class ProofIndex: tails = _tails(destination) last = {tails[-1]} if tails else set() hashes = { - v for f in (*HASH_FIELDS, "alt_md5") for v in _hash_values(entry, f) + v for f in (*HASH_FIELDS, "alt_md5") for v in hash_values(entry, f) } # "/" + d in "/" + path: d is a run of whole segments ending in "/", # so it is a run of the path's segments before the last one. @@ -275,7 +275,7 @@ def removal_candidates( by_system: dict[str, list[str]] = {} for key in sorted(examined): for sid in profiles[key].get("systems") or []: - by_system.setdefault(_norm_system_id(str(sid)), []).append(key) + by_system.setdefault(norm_system_id(str(sid)), []).append(key) romset_cores = {key for key in examined if _loads_romsets(profiles[key])} @@ -287,7 +287,7 @@ def removal_candidates( if evidence.proof(entry.platform, entry.destination) is not None: continue slug = system_of.get(id(entry.platform), entry.native_system) - cores = by_system.get(_norm_system_id(slug), []) + cores = by_system.get(norm_system_id(slug), []) readers = ( [c for c in cores if c in romset_cores] if entry.name.casefold().endswith(_ARCHIVES) else [] @@ -370,7 +370,7 @@ class EntryCategories: self._by_system: dict[str, list[str]] = {} for key in sorted(examined): for sid in profiles[key].get("systems") or []: - self._by_system.setdefault(_norm_system_id(str(sid)), []).append(key) + self._by_system.setdefault(norm_system_id(str(sid)), []).append(key) # Where the platform says which cores run a system, those settle its # entries: an unprofiled core of another system has no say. self._system_runs: dict[str, tuple[list[str], list[str]]] = {} @@ -461,7 +461,7 @@ class EntryCategories: if system in self._system_runs: system_cores, unresolved = self._system_runs[system] else: - system_cores = self._by_system.get(_norm_system_id(system), []) + system_cores = self._by_system.get(norm_system_id(system), []) unresolved = self._unresolved # A reader that runs the entry's system comes first and says so: a # core of another system may only share the file's name. diff --git a/scripts/resolve/collisions.py b/scripts/resolve/collisions.py index e3d831290..bac2b43a5 100644 --- a/scripts/resolve/collisions.py +++ b/scripts/resolve/collisions.py @@ -9,10 +9,10 @@ from dataclasses import dataclass, field from core.hashing import compute_hashes, parse_md5_list from core.ziptools import check_inside_zip from resolve.localfile import resolve_local_file, variant_base_name -from resolve.packfiles import _records_by_path, preferred_entries +from resolve.packfiles import records_by_path, preferred_entries -def _normalize(destination: str, fold: bool = True) -> str: +def comparable_destination(destination: str, fold: bool = True) -> str: """Comparable form of a destination, since layers write it differently. Case is folded only where the platform's filesystem folds it: on Linux @@ -66,7 +66,7 @@ def find_collisions( continue dest = entry.get("destination") or entry.get("name") or "" if dest: - by_dest.setdefault(_normalize(dest, fold), []).append((sys_id, entry)) + by_dest.setdefault(comparable_destination(dest, fold), []).append((sys_id, entry)) collisions = [] for key, claims in sorted(by_dest.items()): @@ -90,7 +90,7 @@ def find_collisions( # A file every declaration accepts settles the path: RetroDECK # declares ATARIOSB.ROM twice, the second with an md5 list that # also names the first one's file. - if any(_accepted_by_all(path, entries, db) for path in resolved): + if any(accepted_by_all(path, entries, db) for path in resolved): continue reached = sorted( (sys_id, local) @@ -112,7 +112,7 @@ def find_collisions( return collisions -def _lists_hashes(entry: dict) -> bool: +def lists_hashes(entry: dict) -> bool: """Whether a declaration says anything about content at all.""" return any( _declared_hashes(entry, field_name) @@ -142,10 +142,10 @@ def _record_at(path: str, db: dict) -> dict | None: path verify --all and slots.py both take. The index is the pack resolver's, so one run holds one copy of it. """ - return _records_by_path(db).get(path) + return records_by_path(db).get(path) -def _content_sha1(path: str, db: dict) -> str | None: +def content_sha1(path: str, db: dict) -> str | None: """The sha1 of the file at path, from the database or read from disk. A data directory cache is not in the database, so its files are hashed. @@ -158,7 +158,7 @@ def _content_sha1(path: str, db: dict) -> str | None: return compute_hashes(path, frozenset({"sha1"}))["sha1"] -def _accepted_by_all(path: str, entries: list[dict], db: dict) -> bool: +def accepted_by_all(path: str, entries: list[dict], db: dict) -> bool: """Whether every declaration's own hashes accept the file at path.""" record = _record_at(path, db) if record is None: diff --git a/scripts/resolve/contentlayout.py b/scripts/resolve/contentlayout.py index 6edae408c..1b2cdda2e 100644 --- a/scripts/resolve/contentlayout.py +++ b/scripts/resolve/contentlayout.py @@ -14,7 +14,7 @@ from resolve.layout import ( CONTENT_TAG_PREFIXES, OUTSIDE_BIOS_FOLDER, ROM_SEARCH_PREFIX, - _placed_entry, + placed_entry, standalone_layout_path, ) from model.declarations import ROMS_ROOT, outer_layout @@ -24,7 +24,7 @@ from core.paths import REPO_ROOT LIBRETRO_RUNNERS = frozenset({"libretro", "retroarch", "retroarch32", "retrorun"}) -def _core_key(name: str) -> str: +def core_key(name: str) -> str: """A core name as two platforms spell it alike: mame2003-plus, mame2003_plus.""" return str(name).lower().replace("-", "_") @@ -83,9 +83,9 @@ def offer_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]: for row in config.get("_rom_folders") or []: folder = str(row.get("folder") or "") offers = row.get("offers") or [] - offered = {(o.get("emulator"), _core_key(o.get("core") or "")) for o in offers} + offered = {(o.get("emulator"), core_key(o.get("core") or "")) for o in offers} choices: list[tuple[dict, set[str]]] = [] - if row.get("core") and (row.get("emulator"), _core_key(row["core"])) not in offered: + if row.get("core") and (row.get("emulator"), core_key(row["core"])) not in offered: choices.append((row, every)) for key, spec in (row.get("board_defaults") or {}).items(): branch = str(key).replace("=", " ", 1) @@ -96,7 +96,7 @@ def offer_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]: if when else every)) for choice, boards in choices: if choice.get("core") and choice.get("emulator") in LIBRETRO_RUNNERS: - found.setdefault((_core_key(choice["core"]), folder), set()).update(boards) + found.setdefault((core_key(choice["core"]), folder), set()).update(boards) return { pair: None if not names or boards >= every else frozenset(boards) for pair, boards in found.items() @@ -108,10 +108,10 @@ def content_folder_boards(config: dict) -> dict[tuple[str, str], frozenset[str] with the boards it does so on, None for every board.""" pairs: set[tuple[str, str]] = set() for core, systems in (config.get("libretro_systems") or {}).items(): - pairs |= {(_core_key(core), str(s)) for s in systems or []} + pairs |= {(core_key(core), str(s)) for s in systems or []} for system in (config.get("systems") or {}).values(): if isinstance(system, dict) and system.get("native_id"): - pairs |= {(_core_key(c), str(system["native_id"])) for c in system.get("cores") or []} + pairs |= {(core_key(c), str(system["native_id"])) for c in system.get("cores") or []} for record in config.get("launchers") or []: if record.get("kind") == "package" and record.get("build") == "libretro": package = str(record.get("emulator", "")) @@ -120,7 +120,7 @@ def content_folder_boards(config: dict) -> dict[tuple[str, str], frozenset[str] # drivers alone, none of the arcade sets of the core it # shares a repository with. continue - core = _core_key(package.removeprefix("lr-")) + core = core_key(package.removeprefix("lr-")) pairs |= {(core, str(s)) for s in record.get("systems") or []} # Pairs from the platform's own lists hold on every board, an offer on # the boards its frontend writes it for. @@ -156,10 +156,10 @@ def content_folder_tags(config: dict) -> set[str]: boards = content_folder_boards(config) target = config.get(TARGET_KEY) pairs = {pair for pair, on in boards.items() if not target or on is None or target in on} - from resolve.launchers import _roms_place + from resolve.launchers import roms_place_of def place(folder: str) -> list: - return list(_roms_place(config, folder) or ()) + return list(roms_place_of(config, folder) or ()) # Without a board, a core a folder offers on some boards only carries # them, for a manifest the installer narrows to one. @@ -272,7 +272,7 @@ def _roms_entry(entry: dict, tree: str, folder: str, rel: str) -> dict: """The entry placed in a roms folder.""" # Below the roms root inside the install tree (EmuELEC's # /storage/roms): a plain dest the platform prefix skips, as a - # standalone entry placed there (_placed_entry). + # standalone entry placed there (placed_entry). where: dict[str, object] = ( {"unprefixed": True} if tree == "install" else {"root": ROMS_ROOT} ) @@ -361,7 +361,7 @@ def _standalone_content_layout(emu_name: str, view: dict, searches: list) -> dic out.append(f) held = {(f.get("root") or "", f.get("standalone_path") or "")} extra = [ - _placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads + placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads ] extra = [e for e in extra if (e.get("root") or "", e["standalone_path"]) not in held] changed |= bool(extra) @@ -373,7 +373,7 @@ def _standalone_content_layout(emu_name: str, view: dict, searches: list) -> dic changed = True placed = {k: v for k, v in f.items() if k != "unplaced"} out.extend( - _placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads + placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads ) return {**view, "files": out} if changed else view @@ -403,13 +403,13 @@ def content_layout( return {**view, "files": files} if CONTENT_SCOPE_TAG not in tags: return view - names = {_core_key(n) for n in {emu_name, *(str(c) for c in view.get("cores") or [])}} + names = {core_key(n) for n in {emu_name, *(str(c) for c in view.get("cores") or [])}} searches = [ json.loads(t[len(ROM_SEARCH_PREFIX):]) for t in tags if t.startswith(ROM_SEARCH_PREFIX) ] build = "standalone" if standalone else "libretro" - searches = [s for s in searches if _core_key(s[0]) in names and s[6] == build] + searches = [s for s in searches if core_key(s[0]) in names and s[6] == build] if not standalone: return _libretro_content_layout(emu_name, view, tags, names, searches) return _standalone_content_layout(emu_name, view, searches) diff --git a/scripts/resolve/cores.py b/scripts/resolve/cores.py index f4d27140a..579138b29 100644 --- a/scripts/resolve/cores.py +++ b/scripts/resolve/cores.py @@ -10,7 +10,7 @@ from core.cli import suggest_names from core.paths import sanitize_pack_path from model.platforms import load_platform_config from model.profiles import preferred_profile, upstream_profile_index -from model.systems import _norm_system_id, select_systems +from model.systems import norm_system_id, select_systems from model.targets import list_available_targets, load_target_config from core.paths import REPO_ROOT @@ -212,11 +212,11 @@ def _platform_profiles( result |= every_libretro() else: # Fallback: system ID intersection with normalization - norm_plat_systems = {_norm_system_id(s) for s in config.get("systems", {})} + norm_plat_systems = {norm_system_id(s) for s in config.get("systems", {})} result = { name for name, p in profiles.items() - if {_norm_system_id(s) for s in p.get("systems", [])} & norm_plat_systems + if {norm_system_id(s) for s in p.get("systems", [])} & norm_plat_systems and p.get("type") != "alias" and not p.get("built_by") } @@ -311,7 +311,7 @@ def system_core_reach( None, kept whatever is available, there being no information to exclude it. """ - _norm_sid = _norm_system_id + _norm_sid = norm_system_id # Normalized system -> cores, from ALL profiles norm_system_cores: dict[str, set[str]] = {} diff --git a/scripts/resolve/datadirs.py b/scripts/resolve/datadirs.py index 553bef061..6d1a4a08b 100644 --- a/scripts/resolve/datadirs.py +++ b/scripts/resolve/datadirs.py @@ -9,7 +9,7 @@ from collections.abc import Callable from resolve.content import adler32_fits, content_fits, name_match_size_ok -def _resolve_in_data_dirs( +def resolve_in_data_dirs( names_to_try: list[str], data_dir_registry: dict, verdict: Callable[[str], str], @@ -54,7 +54,7 @@ def _resolve_in_data_dirs( return None, mismatch -def _data_dir_tail( +def data_dir_tail( dest_hint: str, data_dir_registry: dict, file_entry: dict, db: dict ) -> str | None: """The cached data-directory file at the destination's own tail. diff --git a/scripts/resolve/launchers.py b/scripts/resolve/launchers.py index 648d9068c..f2e9b6018 100644 --- a/scripts/resolve/launchers.py +++ b/scripts/resolve/launchers.py @@ -205,7 +205,7 @@ def _bios_relative(directory: str, base: str) -> str | None: return None if re.search(r"[\s<>]", relative) else relative -def _directories(record: dict, base: str) -> list[str] | None: +def record_directories(record: dict, base: str) -> list[str] | None: """The directories a record reads, in order. None when the code says none. ``search_dir`` transcribes the code, conditions included: "bios/chihiro, @@ -230,7 +230,7 @@ def _directories(record: dict, base: str) -> list[str] | None: return found -def _names(record: dict) -> list[str]: +def record_names(record: dict) -> list[str]: """The file names a record tries, placeholders expanded in code order.""" expands = record.get("expands") or {} names: list[str] = [] @@ -591,8 +591,8 @@ def launcher_places( kind = record.get("kind") if kind not in PLACE_KINDS: continue - names = _names(record) - directories = _directories(record, base) + names = record_names(record) + directories = record_directories(record, base) if not names or directories == []: continue anchored = directories is not None @@ -869,7 +869,7 @@ def handed_directories( handles=handles, source_ref=str(record.get("source_ref", "")), roms_place=None if folder is not None else ( - _roms_place(config, folder_in_roms(part, config)) + roms_place_of(config, folder_in_roms(part, config)) or _configs_place(folder_in_configs(part, config)) or _emulators_place(folder_in_emulators(part, config)) ), @@ -893,7 +893,7 @@ def _emulators_place(path: str | None) -> Place | None: return None if path is None else (EMULATORS_TREE, path) -def _roms_place(config: dict, path: str | None) -> Place | None: +def roms_place_of(config: dict, path: str | None) -> Place | None: """A path below the roms root as a place: in the install tree when the platform installs above its BIOS folder (AmberELEC), else the roms tree.""" if path is None: @@ -984,7 +984,7 @@ def executed_files(config: dict) -> list[ExecutedFile]: if str(record.get("passes_to") or "").strip() != "exec": continue raw = str(record.get("search_dir") or "").strip() - directories = _directories(record, base) + directories = record_directories(record, base) roms = folder_in_roms(raw, config) if raw and not directories else None emulator_folder = folder_in_emulators(raw, config) if raw and not directories else None # A program file needs no extension (pico8, vox): the names are @@ -997,7 +997,7 @@ def executed_files(config: dict) -> list[ExecutedFile]: f"{directories[0]}/{name}" if directories[0] else name )) elif roms is not None: - place = _roms_place(config, sanitize_pack_path(f"{roms}/{name}" if roms else name)) + place = roms_place_of(config, sanitize_pack_path(f"{roms}/{name}" if roms else name)) elif emulator_folder is not None: place = (EMULATORS_TREE, sanitize_pack_path(f"{emulator_folder}/{name}")) else: diff --git a/scripts/resolve/layout.py b/scripts/resolve/layout.py index 90f4ec698..9d4436f9e 100644 --- a/scripts/resolve/layout.py +++ b/scripts/resolve/layout.py @@ -127,7 +127,7 @@ def system_dir_path(entry: dict, path: str) -> str: return f"{directory}/{path}" if directory else path -def _handed(standalone_cores: Iterable[str]) -> list: +def handed_from_tags(standalone_cores: Iterable[str]) -> list: """The directories a standalone set carries, as launchers built them.""" from resolve.launchers import HandedDirectory @@ -245,12 +245,12 @@ def standalone_bindings_for( if isinstance(f, dict) and (path := standalone_layout_path(f, profile)) ] return standalone_bindings( - names, declared, _handed(standalone_cores), _executed(standalone_cores), layout, + names, declared, handed_from_tags(standalone_cores), _executed(standalone_cores), layout, pools, systems, ) -def _placed_entry(entry: dict, profile: dict, placed: tuple[str, str]) -> dict: +def placed_entry(entry: dict, profile: dict, placed: tuple[str, str]) -> dict: """A standalone entry moved to the (tree, path) a platform reads it from.""" tree, path = placed moved = {**entry, "standalone_path": path, diff --git a/scripts/resolve/localfile.py b/scripts/resolve/localfile.py index 78e7f2a48..a485b9355 100644 --- a/scripts/resolve/localfile.py +++ b/scripts/resolve/localfile.py @@ -15,9 +15,9 @@ from core.ziptools import check_inside_zip from model.database import get_mame_clone_map from model.profiles import CONTENT_CHECKS from resolve.archives import ( - _covering_archives, - _holding_members, - _warn_unreadable_archive, + covering_archives, + holding_members, + warn_unreadable_archive, contents_members, ) from resolve.content import ( @@ -28,14 +28,14 @@ from resolve.content import ( name_match_size_ok, shape_fits, ) -from resolve.datadirs import _data_dir_tail, _resolve_in_data_dirs +from resolve.datadirs import data_dir_tail, resolve_in_data_dirs from resolve.ownership import ( - _affinity_tokens, - _engine_tree, - _foreign_tree, - _maker_folder, - _own_tree, - _owner_tokens, + affinity_tokens, + engine_tree, + foreign_tree, + maker_folder, + own_tree, + owner_tokens, other_maker, system_makers, ) @@ -145,7 +145,7 @@ def _rank_tail_candidates( candidates = [ h for h in candidates if not path_of(h).endswith("/" + tail) - or not _foreign_tree(path_of(h), owners if start else set(asker)) + or not foreign_tree(path_of(h), owners if start else set(asker)) ] if len(candidates) < 2: return candidates @@ -154,8 +154,8 @@ def _rank_tail_candidates( candidates, key=lambda h: ( len(path_of(h).split("/")) - depth, - not owners & _affinity_tokens(path_of(h).rsplit("/", 1)[0]), - _foreign_tree(path_of(h), owners), + not owners & affinity_tokens(path_of(h).rsplit("/", 1)[0]), + foreign_tree(path_of(h), owners), ), ) @@ -174,15 +174,15 @@ def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str if len(paths) < 2: return paths hint = dest_hint or file_entry.get("path") or file_entry.get("destination") or "" - wanted = _affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "") - owners = _owner_tokens(file_entry) + wanted = affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "") + owners = owner_tokens(file_entry) sized = declares_shape(file_entry) def score(path: str) -> tuple[int, bool, bool, bool, int]: fits = 0 if sized and os.path.exists(path): fits = int(shape_fits(file_entry, path)) - tokens = _affinity_tokens(path.rsplit("/", 1)[0]) + tokens = affinity_tokens(path.rsplit("/", 1)[0]) # The owner's own copy ranks above any shared tree segment: NetherSX2's # shaders/common/ beat armsx2's own fxaa.fx on two directory tokens. # Another emulator's own tree ranks below everything else. @@ -191,8 +191,8 @@ def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str # flycast-dojo, lindbergh-loader and vvvvvv took C-Dogs' 98-line # gamecontrollerdb.txt by index order. return ( - fits, bool(owners & tokens), not _foreign_tree(path, owners | wanted), - not _engine_tree(path, owners | wanted), len(wanted & tokens), + fits, bool(owners & tokens), not foreign_tree(path, owners | wanted), + not engine_tree(path, owners | wanted), len(wanted & tokens), ) return sorted(paths, key=score, reverse=True) @@ -424,7 +424,7 @@ def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> lis """The records a destination tail names, ranked, ambiguity read.""" candidates = _rank_tail_candidates( q.by_path_suffix.get(tail, []), start, tail, q.files_db, owners, - frozenset(_owner_tokens(q.file_entry)), + frozenset(owner_tokens(q.file_entry)), ) raw = q.by_path_suffix.get(tail, []) if start and len(raw) > 1: @@ -436,7 +436,7 @@ def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> lis # tree still answers a tail several files share. candidates = [ h for h in candidates - if _own_tree(q.files_db.get(h, {}).get("path", ""), owners) + if own_tree(q.files_db.get(h, {}).get("path", ""), owners) ] return candidates @@ -490,7 +490,7 @@ def _by_path_suffix(q: _Lookup) -> tuple[Resolution | None, bool]: hint_parts = q.dest_hint.split("/") # The asking profile and the destination's own directories both name # whose tree a copy may come from. - owners = _owner_tokens(q.file_entry) | _affinity_tokens("/".join(hint_parts[:-1])) + owners = owner_tokens(q.file_entry) | affinity_tokens("/".join(hint_parts[:-1])) for start in range(min(2, len(hint_parts) - 1)): candidates = _tail_candidates(q, start, "/".join(hint_parts[start:]), owners) if start and len(candidates) > 1: @@ -526,9 +526,9 @@ def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution tail_hint and data_dir_registry and not q.has_strong_hash - and not _owner_tokens(q.file_entry) + and not owner_tokens(q.file_entry) ): - hit = _data_dir_tail(tail_hint, data_dir_registry, q.file_entry, q.db) + hit = data_dir_tail(tail_hint, data_dir_registry, q.file_entry, q.db) if hit: return hit, "path_exact" return None @@ -609,7 +609,7 @@ def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str] for match_sha1 in folded.get(try_name.casefold(), []): if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): path = q.files_db[match_sha1]["path"] - if _foreign_tree(path, owners): + if foreign_tree(path, owners): continue if os.path.exists(path) and path not in candidates: candidates.append(path) @@ -630,7 +630,7 @@ def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> li for match_sha1 in shadowed.get(try_name, []): path = q.files_db.get(match_sha1, {}).get("path", "") if ( - _maker_folder(path, str(q.db.get("bios_dir") or "bios")) + maker_folder(path, str(q.db.get("bios_dir") or "bios")) in makers and _name_size_ok(q, match_sha1) and os.path.exists(path) @@ -656,19 +656,19 @@ def _choose_by_name( # Demul's naomi.zip holds more NAOMI BIOS rows than any MAME # set and broke the superset the MAME cores were served. candidates = [ - p for p in candidates if not _foreign_tree(p, owners) + p for p in candidates if not foreign_tree(p, owners) ] or candidates if members: - candidates = _holding_members(candidates, members) + candidates = holding_members(candidates, members) elif len(candidates) > 1 and q.name.casefold().endswith(".zip"): - candidates = _covering_archives(candidates) + candidates = covering_archives(candidates) candidates = _by_affinity(candidates, q.file_entry, q.dest_hint) best = candidates[0] if candidates else "" # A copy outside another emulator's tree comes first: the # affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served # upstream PCSX2 the patches.zip of ARMSX2. candidates = [ - p for p in candidates if not _foreign_tree(p, owners) + p for p in candidates if not foreign_tree(p, owners) ] or candidates primary = [p for p in candidates if "/.variants/" not in p] if not (primary or candidates): @@ -682,8 +682,8 @@ def _choose_by_name( # 8 KB copy was set aside, while data/bluemsx held its own, # and MSX2P.ROM of another dump once only msx-emu answered # the exact casing. - if data_dir_registry and (exact_foreign or _foreign_tree(best, owners)): - hit, _mismatch = _resolve_in_data_dirs( + if data_dir_registry and (exact_foreign or foreign_tree(best, owners)): + hit, _mismatch = resolve_in_data_dirs( q.names_to_try, data_dir_registry, functools.partial( declared_hash_verdict, @@ -714,11 +714,11 @@ def _by_name( candidates = _exact_name_candidates(q) if candidates and all("/.variants/" in p for p in candidates): _add_variant_primaries(q, candidates) - owners = _owner_tokens(q.file_entry) + owners = owner_tokens(q.file_entry) # Only another emulator's tree answers the exact casing: what it # holds there says nothing about this entry's file. exact_foreign = bool(candidates) and all( - _foreign_tree(p, owners) for p in candidates + foreign_tree(p, owners) for p in candidates ) if not candidates or exact_foreign: _add_casefold_candidates(q, candidates, owners) @@ -730,13 +730,13 @@ def _by_name( core_owners = { token for core in q.file_entry.get("platform_cores") or () - for token in _affinity_tokens(str(core)) + for token in affinity_tokens(str(core)) } if ( not owners and core_owners and candidates - and all(_foreign_tree(p, core_owners) for p in candidates) + and all(foreign_tree(p, core_owners) for p in candidates) ): return None, True if makers and candidates: @@ -803,7 +803,7 @@ def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Re ): return path, "md5_composite_exact" except (zipfile.BadZipFile, OSError) as exc: - _warn_unreadable_archive(path, exc) + warn_unreadable_archive(path, exc) if db_md5.lower() in md5_set and not q.composite_only: return path, "md5_exact" return None @@ -821,7 +821,7 @@ def _zipped_named( if zipped_file.casefold() in inner_names: valid.append((path, m, size)) except (zipfile.BadZipFile, OSError) as exc: - _warn_unreadable_archive(path, exc) + warn_unreadable_archive(path, exc) # The archive whose member carries the declared md5 is the one: # neogeo.zip is held twice, each with its own sfix.sfix, and the # first by name was returned as a mismatch while the other matched. @@ -909,7 +909,7 @@ def _in_data_dirs(q: _Lookup, data_dir_registry: dict) -> tuple[Resolution | Non file_entry=q.file_entry, db=q.db, ) - return _resolve_in_data_dirs(q.names_to_try, data_dir_registry, verdict) + return resolve_in_data_dirs(q.names_to_try, data_dir_registry, verdict) def _resolve_layout( diff --git a/scripts/resolve/ownership.py b/scripts/resolve/ownership.py index 0ec3505db..0aea02b5c 100644 --- a/scripts/resolve/ownership.py +++ b/scripts/resolve/ownership.py @@ -16,7 +16,7 @@ def names_manufacturer(sys_id: str, manufacturer: str) -> bool: return sys_id == slug or sys_id.startswith(f"{slug}-") -def _maker_folder(path: str, bios_dir: str) -> str | None: +def maker_folder(path: str, bios_dir: str) -> str | None: """The bios// folder a collection path is filed under.""" prefix = f"{bios_dir.rstrip('/')}/" if not path.startswith(prefix): @@ -40,7 +40,7 @@ def _maker_folders(db: dict) -> frozenset[str]: folders = frozenset( folder for entry in files_db.values() - if (folder := _maker_folder(str(entry.get("path", "")), bios_dir)) + if (folder := maker_folder(str(entry.get("path", "")), bios_dir)) and folder not in BUCKET_FOLDERS ) _maker_folders_cache[:] = [(files_db, len(files_db), folders)] @@ -55,7 +55,7 @@ def system_makers(file_entry: dict, db: dict) -> frozenset[str]: (pc88, arcade), so nothing is narrowed there. """ sys_id = str(file_entry.get("platform_system") or "") - if not sys_id or _owner_tokens(file_entry): + if not sys_id or owner_tokens(file_entry): return frozenset() return frozenset( folder for folder in _maker_folders(db) if names_manufacturer(sys_id, folder) @@ -66,11 +66,11 @@ def other_maker(path: str, makers: frozenset[str], db: dict) -> bool: """Whether a path is filed under a maker the entry's system does not name.""" if not makers: return False - folder = _maker_folder(path, str(db.get("bios_dir") or "bios")) + folder = maker_folder(path, str(db.get("bios_dir") or "bios")) return folder is not None and folder not in BUCKET_FOLDERS and folder not in makers -def _affinity_tokens(text: str) -> set[str]: +def affinity_tokens(text: str) -> set[str]: return { token for token in (re.sub(r"[^0-9a-z]", "", part.casefold()) for part in text.split("/")) @@ -78,7 +78,7 @@ def _affinity_tokens(text: str) -> set[str]: } -def _owner_tokens(file_entry: dict) -> set[str]: +def owner_tokens(file_entry: dict) -> set[str]: """Tokens naming the profile that asks for the file. A profile named after another with a suffix (cxbx-reloaded-2023, @@ -90,14 +90,14 @@ def _owner_tokens(file_entry: dict) -> set[str]: tokens: set[str] = set() for owner in (file_entry.get("source_profile"), file_entry.get("source_emulator")): if owner: - tokens |= _affinity_tokens(str(owner).replace(" ", "")) + tokens |= affinity_tokens(str(owner).replace(" ", "")) profile = str(file_entry.get("source_profile") or "").casefold() words = [word for word in re.split(r"[^0-9a-z]+", profile) if word] tokens |= {"".join(words[:end]) for end in range(1, len(words))} return tokens -def _foreign_tree(path: str, owners: set[str]) -> bool: +def foreign_tree(path: str, owners: set[str]) -> bool: """Whether a path lives in the tree of an emulator that is not the asker. bios/Other// holds what one emulator ships. A same-named file @@ -108,20 +108,20 @@ def _foreign_tree(path: str, owners: set[str]) -> bool: parts = path.split("/") if not owners or len(parts) < 4 or parts[0] != "bios" or parts[1] != "Other": return False - return not (owners & _affinity_tokens(parts[2])) + return not (owners & affinity_tokens(parts[2])) -def _engine_tree(path: str, owners: set[str]) -> bool: +def engine_tree(path: str, owners: set[str]) -> bool: """Whether a path lives in another game's folder under bios/Game Engines/.""" parts = path.split("/") if len(parts) < 4 or parts[0] != "bios" or parts[1] != "Game Engines": return False - return not (owners & _affinity_tokens(parts[2])) + return not (owners & affinity_tokens(parts[2])) -def _own_tree(path: str, owners: set[str]) -> bool: +def own_tree(path: str, owners: set[str]) -> bool: """Whether a path lives in the bios/Other// tree of the asker.""" parts = path.split("/") if not owners or len(parts) < 4 or parts[0] != "bios" or parts[1] != "Other": return False - return bool(owners & _affinity_tokens(parts[2])) + return bool(owners & affinity_tokens(parts[2])) diff --git a/scripts/resolve/packfiles.py b/scripts/resolve/packfiles.py index 6887fd907..3a7804a8b 100644 --- a/scripts/resolve/packfiles.py +++ b/scripts/resolve/packfiles.py @@ -21,13 +21,13 @@ from core.paths import REPO_ROOT, declared_destination from resolve.validation import inner_rom_check # CLI-wide network policy. Public helpers can override it explicitly, while # every CLI mode inherits --offline (including large-file release fallback). -_OFFLINE = False +OFFLINE = False def set_offline(value: bool) -> None: """Forbid every network reach for the rest of the run.""" - global _OFFLINE - _OFFLINE = value + global OFFLINE + OFFLINE = value def scratch_dir() -> str: @@ -61,7 +61,7 @@ def download_external( if declared is None: print(f" WARNING: no hash for {name}, skipping unverifiable download") return False - if _OFFLINE if offline is None else offline: + if OFFLINE if offline is None else offline: print(f" WARNING: {name} is external and the run is offline, not fetched") return False algo, expected = declared @@ -140,7 +140,7 @@ def _verified_asset( def run_is_offline(offline: bool | None = None) -> bool: """Whether this run fetches nothing: --offline, or RETROBIOS_OFFLINE.""" return bool( - (_OFFLINE if offline is None else offline) + (OFFLINE if offline is None else offline) or os.environ.get("RETROBIOS_OFFLINE") ) @@ -148,7 +148,7 @@ def run_is_offline(offline: bool | None = None) -> bool: _RECORDS_BY_PATH: list[tuple[dict, int, dict[str, dict]]] = [] -def _records_by_path(db: dict) -> dict[str, dict]: +def records_by_path(db: dict) -> dict[str, dict]: """The database records by path, built once per database.""" files = db.get("files", {}) if _RECORDS_BY_PATH: @@ -185,7 +185,7 @@ def pending_release_asset( assets = set(asset_candidates(name, registered)) if not assets: return None - records = _records_by_path(db) + records = records_by_path(db) declared_size = file_entry.get("size") for path, asset in sorted(asset_names(registered).items()): record = records.get(path) @@ -396,7 +396,7 @@ def resolve_file( # exactly what the flag forbids. return (path, status) if path else (None, "not_found") cached = _verified_asset( - name, declared, file_entry, _OFFLINE if offline is None else offline, + name, declared, file_entry, OFFLINE if offline is None else offline, ) if cached: return cached, "release_asset" diff --git a/scripts/resolve/reconcile.py b/scripts/resolve/reconcile.py index 73f405917..dfc416f58 100644 --- a/scripts/resolve/reconcile.py +++ b/scripts/resolve/reconcile.py @@ -17,13 +17,13 @@ from collections.abc import Callable from dataclasses import dataclass, field -from model.systems import _norm_system_id +from model.systems import norm_system_id from core.paths import REPO_ROOT HASH_FIELDS = ("sha1", "md5", "sha256", "crc32") -def _hash_values(entry: dict, field_name: str) -> list[str]: +def hash_values(entry: dict, field_name: str) -> list[str]: """Return a hash field as a list, whatever shape it was written in.""" raw = entry.get(field_name) if not raw: @@ -62,8 +62,8 @@ def checked_hashes(entry: dict | None) -> dict | None: kinds = {str(k) for k in raw} else: kinds = {str(raw)} - checked = [f for f in HASH_FIELDS if f in kinds and _hash_values(entry, f)] - if checked and all(len(set(_hash_values(entry, f))) == 1 for f in checked): + checked = [f for f in HASH_FIELDS if f in kinds and hash_values(entry, f)] + if checked and all(len(set(hash_values(entry, f))) == 1 for f in checked): return entry return {k: v for k, v in entry.items() if k not in HASH_FIELDS or k in kinds} @@ -96,8 +96,8 @@ def contradicted_hashes(truth_entry: dict, platform_entry: dict | None) -> list[ theirs = comparable(platform_entry) return [ field_name for field_name in HASH_FIELDS - if (ours := set(_hash_values(checked, field_name))) - and (held := set(_hash_values(theirs, field_name))) + if (ours := set(hash_values(checked, field_name))) + and (held := set(hash_values(theirs, field_name))) and not ours & held ] @@ -111,15 +111,15 @@ def is_label(entry: dict) -> bool: return bool(entry.get("_cores")) and "_named_by" in entry and not entry["_named_by"] -def _is_placeholder(name: str) -> bool: +def is_placeholder(name: str) -> bool: return "<" in name or ">" in name or "*" in name def _field_sets(entry: dict | None) -> dict[str, set[str]]: - return {f: set(_hash_values(entry or {}, f)) for f in HASH_FIELDS} + return {f: set(hash_values(entry or {}, f)) for f in HASH_FIELDS} -def _single_size(value: int | str | list[int | str]) -> int | None: +def single_size(value: int | str | list[int | str]) -> int | None: """One size, or None: a list names several accepted revisions, which a single size field cannot state (int() on it stopped the whole export).""" if isinstance(value, list): @@ -206,9 +206,9 @@ class NativeFile: rejects a file will reject it whatever the platform declares. """ if field_name == "md5" and self.composite_md5: - return _hash_values(self.platform or {}, field_name) - truth_values = _hash_values(self._checked_truth, field_name) - platform_values = _hash_values(self.platform or {}, field_name) + return hash_values(self.platform or {}, field_name) + truth_values = hash_values(self._checked_truth, field_name) + platform_values = hash_values(self.platform or {}, field_name) source = self._identity_source() if source == "platform": return platform_values @@ -242,11 +242,11 @@ class NativeFile: is written when it names one value, which is then that dump's. """ if field_name == "md5" and self.composite_md5: - values = _hash_values(self.platform or {}, field_name) + values = hash_values(self.platform or {}, field_name) return values[0] if values else "" source = self._identity_source() - truth_values = _hash_values(self._checked_truth, field_name) - platform_values = _hash_values(self.platform or {}, field_name) + truth_values = hash_values(self._checked_truth, field_name) + platform_values = hash_values(self.platform or {}, field_name) if source == "truth": return truth_values[0] if truth_values else "" if source == "platform" or not truth_values: @@ -305,7 +305,7 @@ class NativeFile: for entry in order: if not entry or not entry.get("size"): continue - single = _single_size(entry["size"]) + single = single_size(entry["size"]) if single is None: if accepted is None: accepted = {int(v) for v in entry["size"]} @@ -425,19 +425,19 @@ def by_name(truth_entry: dict, platform_entry: dict) -> bool: def by_hash(truth_entry: dict, platform_entry: dict) -> bool: """A value on any of the four hash fields in common: a renamed file.""" - ours = {v for f in HASH_FIELDS for v in _hash_values(truth_entry, f)} + ours = {v for f in HASH_FIELDS for v in hash_values(truth_entry, f)} if not ours: return False theirs = comparable(platform_entry) - return bool(ours & {v for f in HASH_FIELDS for v in _hash_values(theirs, f)}) + return bool(ours & {v for f in HASH_FIELDS for v in hash_values(theirs, f)}) def _contradicts(truth_entry: dict, platform_entry: dict) -> bool: """A hash both entries declare, without a value in common.""" platform_entry = comparable(platform_entry) return any( - (ours := set(_hash_values(truth_entry, f))) - and (theirs := set(_hash_values(platform_entry, f))) + (ours := set(hash_values(truth_entry, f))) + and (theirs := set(hash_values(platform_entry, f))) and not ours & theirs for f in HASH_FIELDS ) @@ -541,7 +541,7 @@ def _correct_matched(matched: NativeFile, truth_entry: dict, report: Report) -> report.hashes_corrected.append( f"{matched.native_system}/{matched.name} {field_name}" ) - elif _hash_values(checked, field_name) and not _hash_values( + elif hash_values(checked, field_name) and not hash_values( comparable(matched.platform), field_name ): matched.filled.append(field_name) @@ -581,7 +581,7 @@ class _TruthPass: def __post_init__(self) -> None: scraped_systems = self.scraped_systems self.norm_to_scraped = { - _norm_system_id(key): key for key in scraped_systems + norm_system_id(key): key for key in scraped_systems } self.platform_ids = { native_id @@ -593,7 +593,7 @@ class _TruthPass: } self.native_by_norm = {} for system in self.systems.values(): - self.native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id) + self.native_by_norm.setdefault(norm_system_id(system.native_id), system.native_id) def target_native_ids(self, truth_sid: str) -> tuple[list[str], bool]: """The native ids a truth system spans, and whether the first one @@ -601,7 +601,7 @@ class _TruthPass: scraped_systems = self.scraped_systems scraped_key = truth_sid if truth_sid in scraped_systems else None if scraped_key is None: - scraped_key = self.norm_to_scraped.get(_norm_system_id(truth_sid)) + scraped_key = self.norm_to_scraped.get(norm_system_id(truth_sid)) if scraped_key is not None: sys_data = scraped_systems[scraped_key] ids = { @@ -620,7 +620,7 @@ class _TruthPass: ordered.remove(primary) ordered.insert(0, primary) return ordered, primary in ids or len(ordered) == 1 - direct = self.native_by_norm.get(_norm_system_id(truth_sid)) + direct = self.native_by_norm.get(norm_system_id(truth_sid)) return ([direct] if direct else [truth_sid]), True def _files_of(self, target_ids: list[str]) -> list[NativeFile]: @@ -639,7 +639,7 @@ class _TruthPass: truth_files = [ entry for entry in truth_files if (name := str(entry.get("name", ""))) - and not name.startswith("_") and not _is_placeholder(name) + and not name.startswith("_") and not is_placeholder(name) ] candidates = [c for c in self._files_of(target_ids) if c.truth is None] pairs = pair_entries(truth_files, [c.platform or {} for c in candidates]) diff --git a/scripts/resolve/review.py b/scripts/resolve/review.py index 3979bd6df..640e4ef6b 100644 --- a/scripts/resolve/review.py +++ b/scripts/resolve/review.py @@ -16,7 +16,7 @@ except ImportError: yaml = None from core.hashing import compute_hashes, parse_hash_list, parse_md5_list, stream_hashes -from model.nodedup import _in_nodedup_dir +from model.nodedup import in_nodedup_dir from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from model.registry import list_registered_platforms @@ -467,7 +467,7 @@ def _check_duplicate(result: ValidationResult, db: dict, relative: str) -> None: # PR that regenerated database.json was told each new file # duplicated itself. result.add_check(True, "Already in the database at this path") - elif _in_nodedup_dir(relative): + elif in_nodedup_dir(relative): result.add_info( f"Identical to `{existing['path']}`, kept: this tree is read by path" ) diff --git a/scripts/resolve/standalone.py b/scripts/resolve/standalone.py index e8f2104d3..d9dc3ca00 100644 --- a/scripts/resolve/standalone.py +++ b/scripts/resolve/standalone.py @@ -8,7 +8,7 @@ from collections.abc import Iterable, Mapping from dataclasses import dataclass from model.profiles import load_emulator_profiles -from model.systems import _norm_system_id +from model.systems import norm_system_id from resolve.contentlayout import content_folder_tags, content_layout from resolve.layout import ( CONTENT_TAG_PREFIXES, @@ -20,8 +20,8 @@ from resolve.layout import ( OUTSIDE_BIOS_FOLDER, OWN_BUILD_PREFIX, SYSTEM_FILE_PREFIX, - _handed, - _placed_entry, + handed_from_tags, + placed_entry, core_system_dirs, entry_launch_systems, runs_standalone, @@ -131,7 +131,7 @@ def standalone_set(config: dict) -> set[str]: natives = native_systems(config) names |= { SYSTEM_FILE_PREFIX + json.dumps( - [natives.get(str(native), str(native)), MACHINE_KEY + _norm_system_id(str(m))] + [natives.get(str(native), str(native)), MACHINE_KEY + norm_system_id(str(m))] ) for record in config.get("launchers") or [] for native in record.get("systems") or [] @@ -196,7 +196,7 @@ class _StandaloneLaunches: names = {emu_name, *(str(c) for c in profile.get("cores") or [])} per_system = bool( profile.get("standalone_directories") or profile.get("standalone_pools") - ) and any(h.systems and h.emulator in names for h in _handed(standalone_cores)) + ) and any(h.systems and h.emulator in names for h in handed_from_tags(standalone_cores)) index = system_file_index(standalone_cores) if per_system else {} # A profile system the platform launches under a system of its own, as # its list says for one entry, is launched there for every entry: @@ -212,7 +212,7 @@ class _StandaloneLaunches: # the folder its record gives, every other launch the folder the records # naming none give. named_systems = frozenset().union(*( - h.systems for h in _handed(standalone_cores) if h.emulator in names + h.systems for h in handed_from_tags(standalone_cores) if h.emulator in names )) if per_system else frozenset() # The layout folders a search setting stands for (standalone_pools): @@ -237,7 +237,7 @@ class _StandaloneLaunches: # own system selects the launch that offers it as a machine # (RetroBat runs XRoar's coco3 under coco). systems = systems.union(*( - self.index.get(MACHINE_KEY + _norm_system_id(s), set()) for s in own + self.index.get(MACHINE_KEY + norm_system_id(s), set()) for s in own )) return systems @@ -298,7 +298,7 @@ class _StandaloneLaunches: # -hash bios/mame/hash (Mame64.Generator.cs:172, 177-178), and # the hash/ beside mame.exe is no longer read. moved = {k: v for k, v in f.items() if k != "bundled"} - files.extend(_placed_entry(moved, self.profile, placed) for placed in places) + files.extend(placed_entry(moved, self.profile, placed) for placed in places) return files diff --git a/scripts/resolve/truth.py b/scripts/resolve/truth.py index 0465d7b10..393ed70ae 100644 --- a/scripts/resolve/truth.py +++ b/scripts/resolve/truth.py @@ -12,7 +12,7 @@ import sys from dataclasses import dataclass from model.declarations import OUTER_ROOTS -from model.systems import _norm_system_id +from model.systems import norm_system_id from model.registry import load_data_dir_registry from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set from resolve.cores import resolve_platform_cores @@ -676,7 +676,7 @@ class _SystemMap: declared_by_name.setdefault(fname, []).append((psid, fe)) norm_to_platform: dict[str, str] = {} for psid in config.get("systems", {}): - norm_to_platform.setdefault(_norm_system_id(psid), psid) + norm_to_platform.setdefault(norm_system_id(psid), psid) return cls( set(config.get("systems", {}).keys()), declared_by_name, norm_to_platform, db, ) @@ -685,7 +685,7 @@ class _SystemMap: """Map a profile system ID to the platform's system ID.""" if profile_sid in self.platform_sys_ids: return profile_sid - return self.norm_to_platform.get(_norm_system_id(profile_sid), profile_sid) + return self.norm_to_platform.get(norm_system_id(profile_sid), profile_sid) def attribute(self, fe: dict, own: str | None, on_platform: set[str]) -> list[str]: """The platform systems an entry belongs to, [] when nothing decides. @@ -962,12 +962,12 @@ def _diff_system(truth_sys: dict, scraped_sys: dict) -> dict: correct while the export corrected hashes the diff never named. An entry never answers for two. """ - from resolve.reconcile import _is_placeholder, is_label, pair_entries, platform_declares + from resolve.reconcile import is_placeholder, is_label, pair_entries, platform_declares truth_files = [ fe for fe in truth_sys.get("files", []) if fe.get("name") and not fe["name"].startswith("_") - and not _is_placeholder(fe["name"]) + and not is_placeholder(fe["name"]) ] scraped_files = scraped_sys.get("files", []) @@ -1074,7 +1074,7 @@ def _update_summary(summary: dict, sys_div: dict) -> None: def diff_platform_truth(truth: dict, scraped: dict) -> dict: """Compare truth YAML against scraped YAML, returning divergences. - System IDs are matched using normalized forms (via _norm_system_id) to + System IDs are matched using normalized forms (via norm_system_id) to handle naming differences between emulator profiles and scraped platforms (e.g. 'sega-game-gear' vs 'sega-gamegear'). """ @@ -1099,13 +1099,13 @@ def diff_platform_truth(truth: dict, scraped: dict) -> dict: # Build normalized-ID lookup for truth systems norm_to_truth: dict[str, str] = {} for sid in truth_systems: - norm_to_truth[_norm_system_id(sid)] = sid + norm_to_truth[norm_system_id(sid)] = sid # Match scraped systems to truth via normalized IDs matched_truth: set[str] = set() for s_sid in sorted(scraped_systems): - norm = _norm_system_id(s_sid) + norm = norm_system_id(s_sid) t_sid = norm_to_truth.get(norm) if t_sid is None: diff --git a/scripts/resolve/validation.py b/scripts/resolve/validation.py index 3e4a3134d..da9849450 100644 --- a/scripts/resolve/validation.py +++ b/scripts/resolve/validation.py @@ -50,7 +50,7 @@ _CONTENT_REASONS = { _HASH_CHECKS = frozenset({"crc32", "md5", "sha1", "adler32"}) -def _parse_validation(validation: list | dict | None) -> list[str]: +def parse_validation(validation: list | dict | None) -> list[str]: """Extract the validation check list from a file's validation field. Handles both simple list and divergent (core/upstream) dict forms. @@ -378,7 +378,7 @@ def _index_entry(index: dict[str, dict], emu_name: str, f: dict, checks: list[st _merge_per_emulator(item, emu_name, f, checks) -def _build_validation_index(profiles: dict) -> dict[str, dict]: +def build_validation_index(profiles: dict) -> dict[str, dict]: """Build per-filename validation rules from emulator profiles. Returns {filename: {"checks": [str], "size": int|None, "min_size": int|None, @@ -407,7 +407,7 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]: fname = f.get("name", "") if not fname: continue - checks = _parse_validation(f.get("validation")) + checks = parse_validation(f.get("validation")) slot = (fname, emu_name, f.get("path") or fname) if not checks: unchecked.add(slot) diff --git a/scripts/romrecipes/build.py b/scripts/romrecipes/build.py index 751e38257..dddc04e50 100644 --- a/scripts/romrecipes/build.py +++ b/scripts/romrecipes/build.py @@ -11,7 +11,7 @@ from core.hashing import compute_hashes from core.paths import REPO_ROOT from core.torrentzip import write_torrentzip, zlib_ng_version from romrecipes.ledger import is_archive_path -from romrecipes.members import _member_sha1, _opener +from romrecipes.members import member_sha1, member_opener # --- build ------------------------------------------------------------------ @@ -79,7 +79,7 @@ def _members_match(built: Path, members: list[dict]) -> str: sizes = {info.filename: info.file_size for info in archive.infolist()} crcs = {info.filename: f"{info.CRC:08x}" for info in archive.infolist()} held = sorted( - (name, sizes[name], crcs[name], _member_sha1(built, name)) for name in names + (name, sizes[name], crcs[name], member_sha1(built, name)) for name in names ) if held == expected: return "" @@ -134,7 +134,7 @@ def build_archive( with scratch.open("wb") as handle: write_torrentzip( handle, - [(name, _opener(source.path, source.member)) for name, source in sources], + [(name, member_opener(source.path, source.member)) for name, source in sources], ) if exact: written = compute_hashes(scratch, frozenset({"sha1"}), cache=False)["sha1"] diff --git a/scripts/romrecipes/capture.py b/scripts/romrecipes/capture.py index 0c0884444..7ea253246 100644 --- a/scripts/romrecipes/capture.py +++ b/scripts/romrecipes/capture.py @@ -13,7 +13,7 @@ from typing import BinaryIO from core.hashing import parse_hash_list from core.torrentzip import write_torrentzip, zlib_ng_version from romrecipes.ledger import database_archives -from romrecipes.members import _member_sha1, _opener +from romrecipes.members import member_sha1, member_opener from romrecipes.pins import container_entries from romrecipes.romsets import collect_recipes, load_dat_recipes @@ -65,14 +65,14 @@ def read_archive(path: Path, sha1: str) -> dict: for _attempt in range(2): sink = HashSink() written = write_torrentzip( - sink, [(info.filename, _opener(path, info.filename)) for info in files] + sink, [(info.filename, member_opener(path, info.filename)) for info in files] ) by_name = {member.name: member.sha1 for member in written} if sink.sha1.hexdigest() == sha1: rebuild = "exact" break else: - by_name = {info.filename: _member_sha1(path, info.filename) for info in files} + by_name = {info.filename: member_sha1(path, info.filename) for info in files} record: dict = { "rebuild": rebuild, "members": [ diff --git a/scripts/romrecipes/members.py b/scripts/romrecipes/members.py index 8b8280b6e..a217fe45b 100644 --- a/scripts/romrecipes/members.py +++ b/scripts/romrecipes/members.py @@ -32,12 +32,12 @@ class _Member(io.RawIOBase): super().close() -def _opener(source: Path, member: str | None) -> Callable[[], Readable]: +def member_opener(source: Path, member: str | None) -> Callable[[], Readable]: if member is None: return lambda: source.open("rb") return lambda: _Member(source, member) -def _member_sha1(path: Path, name: str) -> str: +def member_sha1(path: Path, name: str) -> str: with _Member(path, name) as stream: return stream_hashes(stream, frozenset({"sha1"}))["sha1"] diff --git a/scripts/scraper/buildbot_system.py b/scripts/scraper/buildbot_system.py index ca2385f13..d4f9e493e 100644 --- a/scripts/scraper/buildbot_system.py +++ b/scripts/scraper/buildbot_system.py @@ -11,7 +11,7 @@ import urllib.parse import urllib.request from model.safeparse import yaml_load -from model.registry import _load_versions +from model.registry import load_versions log = logging.getLogger(__name__) @@ -76,7 +76,7 @@ def check(registry_path: str = DEFAULT_REGISTRY) -> dict: return {"error": str(exc), "entries": []} tracked = load_tracked_entries(registry_path) - versions = _load_versions() + versions = load_versions() buildbot_set = set(index_zips) tracked_set = set(tracked.keys()) diff --git a/scripts/scraper/emudeck_scraper.py b/scripts/scraper/emudeck_scraper.py index 5cfe7417f..349ccb661 100644 --- a/scripts/scraper/emudeck_scraper.py +++ b/scripts/scraper/emudeck_scraper.py @@ -188,14 +188,14 @@ _RE_ARRAY = re.compile( # checkBIOS.sh declares its checks as `checkPS1BIOS(){`, with no `function` # keyword and no settled casing for BIOS. -_RE_FUNC = re.compile( +RE_FUNC = re.compile( r"^[ \t]*(?:function\s+)?(check\w*(?:BIOS|Bios))\s*\(\)\s*\{", re.MULTILINE, ) # The hash list is named differently in each check (PSBios, hashes, ...), so # it is found by shape rather than by name. -_RE_LOCAL_HASHES = re.compile( +RE_LOCAL_HASHES = re.compile( r"(?:local\s+)?\w+=\(\s*((?:[0-9a-fA-F]{32}\s*)+)\)", re.MULTILINE, ) @@ -276,16 +276,16 @@ class Scraper(BaseScraper): def _parse_function_hashes(self, script: str) -> dict[str, list[str]]: """Extract local hash arrays from named check functions.""" result: dict[str, list[str]] = {} - for func_match in _RE_FUNC.finditer(script): + for func_match in RE_FUNC.finditer(script): func_name = func_match.group(1) if func_name not in FUNCTION_HASH_MAP: continue system = FUNCTION_HASH_MAP[func_name] func_start = func_match.start() - next_func = _RE_FUNC.search(script, func_match.end()) + next_func = RE_FUNC.search(script, func_match.end()) func_end = next_func.start() if next_func else len(script) func_body = script[func_start:func_end] - local_match = _RE_LOCAL_HASHES.search(func_body) + local_match = RE_LOCAL_HASHES.search(func_body) if local_match: hashes_raw = local_match.group(1) hashes = [h.strip() for h in hashes_raw.split() if h.strip()] diff --git a/scripts/scraper/game_dat_importer.py b/scripts/scraper/game_dat_importer.py index c512aa068..ca0893638 100644 --- a/scripts/scraper/game_dat_importer.py +++ b/scripts/scraper/game_dat_importer.py @@ -164,8 +164,8 @@ SERIAL_NOTE = ( _PAREN = re.compile(r"\(([^)]+)\)") _NOINTRO_MEMBER = re.compile(r"^(?P.+) \((?P\d{8}-\d{6})\)\.dat$") -_DISPOSITION = re.compile(r'filename="(?P[^"]+)"') -_REDUMP_FILE = re.compile( +DISPOSITION = re.compile(r'filename="(?P[^"]+)"') +REDUMP_FILE = re.compile( r"^(?P.+) - Datfile \((?P\d+)\) \((?P\d{4}-\d{2}-\d{2}) (?P") -def _date_line() -> str: +def date_line() -> str: """The date a page closes on, in the words of data_as_of(). The search does not read it: a query word such as the "2" of "playstation 2 bios" also matches the start of "2026", and every page closing on the date then held every word of the query.""" return f'
{data_as_of()}.
' - - -_REPO_ROOT = REPO_ROOT diff --git a/scripts/sitegen/consolecards.py b/scripts/sitegen/consolecards.py index d6e1aeb06..47dc7dde1 100644 --- a/scripts/sitegen/consolecards.py +++ b/scripts/sitegen/consolecards.py @@ -5,12 +5,12 @@ from __future__ import annotations import re from typing import TypeVar -from model.collection import _profiles_on_disk +from model.collection import profiles_on_disk from model.composition import GAME_DATA_TOPS from model.guides import INSTALL_PS1, INSTALL_SH from model.profiles import entry_system_ids from packs.crossref import FileConsumers -from sitegen.cards import _emulator_display, _romset_releases, _system_file_card +from sitegen.cards import emulator_display, romset_releases, system_file_card # A manufacturer page above this much Markdown becomes a summary with one @@ -41,7 +41,7 @@ SYSTEM_SUMMARY_HTML = 500_000 FITTED_ADDRESS_CHARS = {INSTALL_PS1: 67, INSTALL_SH: 66} -def _install_box_weight(lines: list[str]) -> int: +def install_box_weight(lines: list[str]) -> int: weight = 0 for line in lines: weight += len(line) + 1 @@ -54,7 +54,7 @@ def _install_box_weight(lines: list[str]) -> int: # A system card: whether it is a variant, its lines, its sha1. Card = tuple[bool, list[str], str] -_Item = TypeVar("_Item") +Item = TypeVar("Item") def _reading_entries(sha1: str, consumers: FileConsumers) -> list[dict]: @@ -68,10 +68,10 @@ def _reading_entries(sha1: str, consumers: FileConsumers) -> list[dict]: return entries -_NO_PRIORITY = 1 << 30 +NO_PRIORITY = 1 << 30 -def _card_rank(f: dict, consumers: FileConsumers, start: dict[str, int] | None = None) -> tuple: +def card_rank(f: dict, consumers: FileConsumers, start: dict[str, int] | None = None) -> tuple: """Where a file's card sits in its console: the files the section's start line names first, in its order (``start``, sha1 -> place), then the files an emulator requires, then by the emulators' search order @@ -89,9 +89,9 @@ def _card_rank(f: dict, consumers: FileConsumers, start: dict[str, int] | None = priorities = [e["priority"] for e in entries if isinstance(e.get("priority"), int)] required = any(e.get("required", True) for e in entries) return ( - (start or {}).get(sha1, _NO_PRIORITY), + (start or {}).get(sha1, NO_PRIORITY), not required, - min(priorities, default=_NO_PRIORITY), + min(priorities, default=NO_PRIORITY), -len(entries) if required else 0, -len(consumers.platforms.get(sha1, ())), f["name"].casefold(), f["name"], f.get("path", ""), @@ -102,7 +102,7 @@ def _by_name(f: dict) -> tuple: return f["name"].casefold(), f["name"], f.get("path", "") -def _console_cards( +def console_cards( manufacturer: str, files: list[dict], consumers: FileConsumers, @@ -120,13 +120,13 @@ def _console_cards( def order(f: dict) -> tuple: if by_name: - return (place.get(str(f.get("sha1", "")), _NO_PRIORITY), *_by_name(f)) - return _card_rank(f, consumers, place) + return (place.get(str(f.get("sha1", "")), NO_PRIORITY), *_by_name(f)) + return card_rank(f, consumers, place) # Another revision of a MAME or FBNeo set is another release's set, its # Romset line saying which: it sits open beside the set of its name. # Twelve neogeo.zip were on five pages, the SNK ones closed under # Variants. - romsets = _romset_releases() + romsets = romset_releases() beside = [f for f in files if "/.variants/" in f["path"] and f["name"] in romsets] main_files = [f for f in files if "/.variants/" not in f["path"]] variant_files = [f for f in files if "/.variants/" in f["path"] and f not in beside] @@ -143,9 +143,9 @@ def _console_cards( elif by_set.get(f["name"]): ordered.extend(by_set.pop(f["name"])) ordered.extend(f for files in by_set.values() for f in files) - cards = [(False, _system_file_card(f, consumers, anchored, searchable), str(f.get("sha1", ""))) + cards = [(False, system_file_card(f, consumers, anchored, searchable), str(f.get("sha1", ""))) for f in ordered] - cards += [(True, _system_file_card(v, consumers, anchored, searchable), str(v.get("sha1", ""))) + cards += [(True, system_file_card(v, consumers, anchored, searchable), str(v.get("sha1", ""))) for v in sorted(variant_files, key=order)] return cards @@ -155,7 +155,7 @@ def _console_cards( START_WITH_NAMES = 6 -def _region_order() -> dict[str, int]: +def region_order() -> dict[str, int]: """The regions a start line lists, the territories first. A file read for every region is a region-free stand-in for the BIOS of each one: the PlayStation section opened on psxonpsp660.bin, which one emulator @@ -169,7 +169,7 @@ def _region_order() -> dict[str, int]: return {region: index for index, region in enumerate(ordered)} -def _reading_pairs(sha1: str, consumers: FileConsumers) -> list[tuple[str, dict]]: +def reading_pairs(sha1: str, consumers: FileConsumers) -> list[tuple[str, dict]]: """The profile entries that read a file, each with its emulator.""" files_of = getattr(consumers, "emulator_files", {}) pairs = [] @@ -180,12 +180,12 @@ def _reading_pairs(sha1: str, consumers: FileConsumers) -> list[tuple[str, dict] return pairs -def _entry_systems(emulator: str, entry: dict) -> list[str]: +def entry_systems(emulator: str, entry: dict) -> list[str]: """The systems an entry is read for: its own `system:` or `systems:` (a MAME device set several systems load), else its profile's only one.""" if entry.get("system") or entry.get("systems"): return entry_system_ids(entry, {}) - systems = (_profiles_on_disk().get(emulator) or {}).get("systems") or [] + systems = (profiles_on_disk().get(emulator) or {}).get("systems") or [] return [str(systems[0])] if len(systems) == 1 else [] @@ -193,7 +193,7 @@ def _entry_systems(emulator: str, entry: dict) -> list[str]: _SECTION_ENTRIES: dict[int, tuple[object, dict[tuple[str, str], list]]] = {} -def _entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]: +def entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]: """Each console section with the (sha1, emulator, entry, system) whose system leads to it, read once per build.""" from sitegen.render import system_section @@ -204,8 +204,8 @@ def _entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list] sections: dict[str, tuple[str, str] | None] = {} index: dict[tuple[str, str], list] = {} for sha1 in sorted(getattr(consumers, "emulator_entries", {})): - for emulator, entry in _reading_pairs(sha1, consumers): - for sys_id in _entry_systems(emulator, entry): + for emulator, entry in reading_pairs(sha1, consumers): + for sys_id in entry_systems(emulator, entry): if sys_id not in sections: sections[sys_id] = system_section(sys_id) place = sections[sys_id] @@ -216,7 +216,7 @@ def _entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list] return index -def _setup_name(f: dict, consumers: FileConsumers, pairs: list[tuple[str, dict]]) -> str: +def setup_name(f: dict, consumers: FileConsumers, pairs: list[tuple[str, dict]]) -> str: """The name most setups give a file, else most emulators: the collection keeps BizHawk's GBA_bios.rom where eight setups write gba_bios.bin.""" counts: dict[str, int] = {} @@ -236,22 +236,22 @@ def _setup_name(f: dict, consumers: FileConsumers, pairs: list[tuple[str, dict]] return f["name"] if f["name"] in top else top[0] -def _without_files(emulators: list[str]) -> str: +def without_files(emulators: list[str]) -> str: """Who runs without the files: every emulator reading one, up to three by name, more counted, as their order would rank nothing.""" - names = sorted({_emulator_display(e) for e in emulators}, key=str.casefold) + names = sorted({emulator_display(e) for e in emulators}, key=str.casefold) if len(names) > 3: return f": none of its {len(names)} emulators requires one" return " with " + (", ".join(names[:-1]) + f" or {names[-1]}" if len(names) > 1 else names[0]) -def _visible(name: str) -> str: +def visible_name(name: str) -> str: """The file name a start line shows, out of its code span and link.""" match = re.match(r"\[?`([^`]*)`", name) return match[1] if match else name -def _add_name(names: list[str], name: str) -> None: +def add_name(names: list[str], name: str) -> None: """A name once per line: two copies of sfcbox.zip read as one file.""" - if all(_visible(n) != _visible(name) for n in names): + if all(visible_name(n) != visible_name(name) for n in names): names.append(name) diff --git a/scripts/sitegen/crossref.py b/scripts/sitegen/crossref.py index d8f0f57be..c421e25dd 100644 --- a/scripts/sitegen/crossref.py +++ b/scripts/sitegen/crossref.py @@ -8,11 +8,11 @@ import urllib.parse from model.systemnames import system_name from resolve.cores import resolve_platform_cores from sitegen import markup -from sitegen.config import _date_line +from sitegen.config import date_line from sitegen.emulatorsindex import CLS_LABEL_ONE -from sitegen.parts import _parent_front_matter -from sitegen.platformpage import OWN_LIST_ONLY, _own_list_only -from sitegen.render import _count, _escape_tags +from sitegen.parts import parent_front_matter +from sitegen.platformpage import OWN_LIST_ONLY, own_list_only +from sitegen.render import count_text, escape_tags def _core_scope_note(config: dict, profiles: dict) -> str: @@ -30,10 +30,10 @@ def _core_scope_note(config: dict, profiles: dict) -> str: others = len(resolved - every_libretro) if not others: return " (all libretro)" - return f" (all libretro, plus {_count(others, 'other core')})" + return f" (all libretro, plus {count_text(others, 'other core')})" -def _gap_sources(data: dict) -> dict[str, int]: +def gap_sources(data: dict) -> dict[str, int]: """Where each undeclared file of one emulator comes from. A file the emulator's own package installs is not one to find. The @@ -106,7 +106,7 @@ def _upstream_label(key: str) -> str: def _breakable(label: str) -> str: """A project address that may wrap after each slash: unbroken, the longest pushed three of five columns off a 1,440 px screen.""" - return "/".join(_escape_tags(part) for part in label.split("/")) + return "/".join(escape_tags(part) for part in label.split("/")) def _xref_platform_rows(config: dict, unique: dict) -> tuple[int, list[str]]: @@ -120,7 +120,7 @@ def _xref_platform_rows(config: dict, unique: dict) -> tuple[int, list[str]]: p = unique[emu_name] cls_raw = p.get("core_classification", "-") systems = p.get("systems", []) or [] - sys_str = ", ".join(_escape_tags(system_name(s)) for s in systems[:3]) + sys_str = ", ".join(escape_tags(system_name(s)) for s in systems[:3]) if len(systems) > 3: sys_str += f" +{len(systems) - 3}" files = p.get("files", []) or [] @@ -134,9 +134,9 @@ def _xref_platform_rows(config: dict, unique: dict) -> tuple[int, list[str]]: upstream = _xref_upstream(p) key, _rest = upstream_project(upstream) upstream_display = (f"[{_breakable(_upstream_label(key))}]({upstream.split()[0]})" - if upstream.startswith("http") else (_escape_tags(upstream) or "-")) + if upstream.startswith("http") else (escape_tags(upstream) or "-")) rows.append( - f"| [{_escape_tags(p.get('emulator', emu_name))}](emulators/{emu_name}.md) " + f"| [{escape_tags(p.get('emulator', emu_name))}](emulators/{emu_name}.md) " f"| {CLS_LABEL_ONE.get(cls_raw, cls_raw)} | {sys_str or '-'} | {file_str} " f"| {upstream_display} |" ) @@ -163,23 +163,23 @@ def _render_xref_by_platform( config = cov["config"] count, rows = _xref_platform_rows(config, unique) stem = f"cross-reference-{pname}" - if _own_list_only(config): + if own_list_only(config): # cores: [] (MiSTer, BizHawk): no profile describes what they # read, and a page of cores would be an empty table. - lines.append(f"| [{_escape_tags(display)}](platforms/{pname}.md) | 0 " + lines.append(f"| [{escape_tags(display)}](platforms/{pname}.md) | 0 " f"| {OWN_LIST_ONLY} |") continue lines.append( - f"| [{_escape_tags(display)}](platforms/{pname}.md) | {count}" - f"{_core_scope_note(config, unique)} | [Cores on {_escape_tags(display)}]({stem}.md) |" + f"| [{escape_tags(display)}](platforms/{pname}.md) | {count}" + f"{_core_scope_note(config, unique)} | [Cores on {escape_tags(display)}]({stem}.md) |" ) if moved is not None: moved[stem] = "\n".join([ "---", "level: reference", - *_parent_front_matter(("Cores by platform", "/cross-reference/")), "---", "", + *parent_front_matter(("Cores by platform", "/cross-reference/")), "---", "", f"# Cores on {display}", "", - f"{_count(count, 'core')}{_core_scope_note(config, unique)} that " + f"{count_text(count, 'core')}{_core_scope_note(config, unique)} that " f"{display} runs, the systems each emulates and the project it comes " f"from. Part of [Cores by platform](cross-reference.md). The files " f"are listed on the [{display} page](platforms/{pname}.md).", @@ -236,7 +236,7 @@ def _render_xref_by_upstream( # The project's own address: the bare one when a core cites it. home = next((u for u in urls if not upstream_project(u)[1]), urls[0]) upstream_cell = (f"[{_breakable(_upstream_label(key))}]({home})" if home.startswith("http") - else _escape_tags(key)) + else escape_tags(key)) lines.append( "| " + ", ".join(f"[{c}](emulators/{c}.md)" for c in cores) + f" | {upstream_cell} | {', '.join(_breakable(r) for r in revisions) or '-'} " @@ -294,5 +294,5 @@ def generate_cross_reference( lines.extend(_render_xref_by_platform(coverages, unique, moved)) lines.extend(_render_xref_by_upstream(coverages, unique)) - lines.extend(["", _date_line()]) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" diff --git a/scripts/sitegen/dataexports.py b/scripts/sitegen/dataexports.py index f6243c42c..62f9be254 100644 --- a/scripts/sitegen/dataexports.py +++ b/scripts/sitegen/dataexports.py @@ -20,21 +20,22 @@ from model import retired as model_retired from model.dumpcatalog import load_provenance_snapshots from packs.crossref import FileConsumers from acquire.provenance import build_report -from sitegen.apiitems import _sha1_by_path, core_index_items, system_index_items -from sitegen.config import DATA_LICENSE, REPO_URL, _REPO_ROOT, _timestamp -from sitegen.install import _release_pack_platforms +from sitegen.apiitems import sha1_index_by_path, core_index_items, system_index_items +from sitegen.config import DATA_LICENSE, REPO_URL, data_timestamp +from core.paths import REPO_ROOT +from sitegen.install import release_pack_platforms from sitegen.lookup import ( HASH_ALGORITHMS, - _hash_values, + sorted_hash_values, data_directory_members, file_location_items, file_lookup_records, write_lookup_shards, ) from sitegen.provenance import load_derivable -from sitegen.publish import _publish_manifests -from sitegen.structured import _write_platform_dats, collection_dat -from sitegen.write import _record, write_if_changed +from sitegen.publish import publish_manifests +from sitegen.structured import write_platform_dats, collection_dat +from sitegen.write import record_written, write_if_changed def generate_stats(stats: dict) -> str: @@ -50,7 +51,7 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict]) "layer": "platform", "owner": row["platform_id"], "system": row["system"], "name": row["name"], "path": row["destination"], "algorithm": algorithm, "value": value, - } for value in _hash_values(row.get(f"{algorithm}_raw", row.get(algorithm)))) + } for value in sorted_hash_values(row.get(f"{algorithm}_raw", row.get(algorithm)))) for item in emulator_items: for entry in item["profile"].get("files", []) or []: if not isinstance(entry, dict): @@ -61,7 +62,7 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict]) "system": _json_text(entry.get("system")), "name": entry.get("name", ""), "path": entry.get("path", "") or "", "algorithm": algorithm, "value": value, - } for value in _hash_values(entry.get(algorithm))) + } for value in sorted_hash_values(entry.get(algorithm))) # Members of an archive: MAME and FBNeo hash the ROMs inside the # set, never the set. Left out, a loose nmk004.bin (crc32 # 83b6f611) found no row while the site search found it. @@ -75,7 +76,7 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict]) "system": _json_text(entry.get("system")), "name": str(member["name"]), "path": f"{archive}/{member['name']}", "algorithm": algorithm, "value": value, - } for value in _hash_values(member.get(algorithm))) + } for value in sorted_hash_values(member.get(algorithm))) rows.sort(key=lambda r: (r["layer"], r["owner"], r["name"], r["algorithm"], r["value"])) return rows @@ -122,7 +123,7 @@ def _verify_outcomes( @functools.lru_cache(maxsize=1) def _contract_keys() -> frozenset[str]: """The top-level keys platform.schema.json allows in a platform's list.""" - schema = json.loads((_REPO_ROOT / "schemas" / "platform.schema.json").read_text(encoding="utf-8")) + schema = json.loads((REPO_ROOT / "schemas" / "platform.schema.json").read_text(encoding="utf-8")) return frozenset(schema.get("properties") or {}) @@ -159,7 +160,7 @@ def _split_contract(config: dict) -> tuple[dict, dict]: # The merged config gives a child its parent's release_pack: Lakka and # RetroPie said true in the API while every page said they had no ZIP. # The registry's own entry decides, as it does for the pages. - released = config.get("_key") in _release_pack_platforms() + released = config.get("_key") in release_pack_platforms() if released or "release_pack" in registry: registry["release_pack"] = released return contract, registry @@ -180,7 +181,7 @@ def _platform_export_rows( """Normalized platform summaries and one row per declared file.""" items: list[dict] = [] file_rows: list[dict] = [] - sha1_by_path = _sha1_by_path(db) + sha1_by_path = sha1_index_by_path(db) for key, coverage in sorted(coverages.items()): config = coverage["config"] outcome = _verify_outcomes(coverage, sha1_by_path) @@ -247,7 +248,7 @@ def build_emulator_gap_report( The gap analysis page and the published gaps export must not compute this twice and drift. Both read this one report. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id from model.declarations import merged_platform_declarations from packs.crossref import cross_reference as run_cross_reference @@ -263,7 +264,7 @@ def build_emulator_gap_report( for fe in system.get("files", []): fname = fe.get("name", "") if fname: - declared.setdefault(_norm_system_id(sys_id), set()).add(fname) + declared.setdefault(norm_system_id(sys_id), set()).add(fname) unique_profiles = { k: v @@ -302,7 +303,7 @@ def _gap_export_rows( A `layer` column keeps the two apart instead of publishing only one. """ rows: list[dict] = [] - sha1_by_path = _sha1_by_path(db) + sha1_by_path = sha1_index_by_path(db) for key, coverage in sorted(coverages.items()): for detail in coverage.get("details", []): if detail.get("status") == "ok" and not detail.get("discrepancy"): @@ -506,10 +507,10 @@ def _write_sqlite_export( CREATE INDEX emulator_files_name_idx ON emulator_files(name); CREATE INDEX gaps_status_idx ON gaps(layer, status); """) - commit = _source_commit() + commit = source_commit() metadata = { "schema_version": "1", - "generated_at": str(db.get("generated_at") or _timestamp()), + "generated_at": str(db.get("generated_at") or data_timestamp()), **({"commit": commit} if commit else {}), "source": REPO_URL, "scope": "metadata only, no BIOS or firmware payload bytes", @@ -640,13 +641,13 @@ def system_export_item(slug: str, manufacturer: str, consoles: dict[str, list]) @functools.lru_cache(maxsize=1) -def _source_commit() -> str: +def source_commit() -> str: """The commit of the checkout the site is built from, empty outside one.""" import subprocess try: result = subprocess.run( - ["git", "rev-parse", "HEAD"], cwd=_REPO_ROOT, + ["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, capture_output=True, text=True, check=True, ) except (OSError, subprocess.CalledProcessError) as error: @@ -694,10 +695,10 @@ def generate_data_exports( for directory in (api, downloads, schemas_dest): directory.mkdir(parents=True, exist_ok=True) - generated_at = str(db.get("generated_at") or _timestamp()) + generated_at = str(db.get("generated_at") or data_timestamp()) # The revision the data was read at: a tool comparing two downloads # could not tell which commit each came from. - commit = _source_commit() + commit = source_commit() stamp = {"commit": commit} if commit else {} platform_items, platform_files = _platform_export_rows(coverages, db) emulator_items = _emulator_export_items(profiles) @@ -715,7 +716,7 @@ def generate_data_exports( } write_lookup_shards( api, file_lookup_records(db, coverages, profiles, locations, members, consumers, - model_retired.load(_REPO_ROOT / "retired.json"), wanted), + model_retired.load(REPO_ROOT / "retired.json"), wanted), generated_at, commit, ) for filename, (kind, items) in envelopes.items(): @@ -744,11 +745,11 @@ def generate_data_exports( # Every schema the published files are written against, the manifests' # too: an integrator had the platform's list and not what the pack writes. - for schema_path in sorted((_REPO_ROOT / "schemas").glob("*.schema.json")): + for schema_path in sorted((REPO_ROOT / "schemas").glob("*.schema.json")): shutil.copy2(schema_path, schemas_dest / schema_path.name) - _record(schemas_dest / schema_path.name) + record_written(schemas_dest / schema_path.name) - manifest_assets = _publish_manifests(api) + manifest_assets = publish_manifests(api) for filename, (kind, items) in { "systems.json": ("system-index", system_index_items(db, coverages, profiles)), "cores.json": ("core-index", core_index_items(profiles)), @@ -774,7 +775,7 @@ def generate_data_exports( ), }) write_if_changed(str(downloads / "retrobios.dat"), collection_dat(db, generated_at)) - platform_dats = _write_platform_dats(downloads / "dat", db, members, generated_at) + platform_dats = write_platform_dats(downloads / "dat", db, members, generated_at) write_if_changed( str(downloads / "files.csv"), _csv_document( @@ -831,7 +832,7 @@ def generate_data_exports( downloads / "retrobios.sqlite", db, platform_items, platform_files, emulator_items, gap_rows, ) - _record(downloads / "retrobios.sqlite") + record_written(downloads / "retrobios.sqlite") write_if_changed( str(downloads / "provenance-wanted.csv"), _csv_document(list(WANTED_FIELDS), wanted), diff --git a/scripts/sitegen/datapage.py b/scripts/sitegen/datapage.py index 540cd126f..a8cd135ab 100644 --- a/scripts/sitegen/datapage.py +++ b/scripts/sitegen/datapage.py @@ -11,8 +11,9 @@ from model import siteinputs from model.registry import load_platform_registry from model.safeparse import yaml_load from sitegen import markup, measurements as sitemeasurements -from sitegen.config import RELEASE_URL, REPO_URL, SITE_URL, _REPO_ROOT -from sitegen.render import _escape_tags, _fmt_size +from sitegen.config import RELEASE_URL, REPO_URL, SITE_URL +from core.paths import REPO_ROOT +from sitegen.render import escape_tags, fmt_size def _is_manifest(item: dict) -> bool: @@ -36,7 +37,7 @@ def _served_schemas() -> list[tuple[str, str]]: the export copies: the page linked 7 of 11.""" return [ (path.name, str(json.loads(path.read_text(encoding="utf-8")).get("title") or path.stem)) - for path in sorted((_REPO_ROOT / "schemas").glob("*.schema.json")) + for path in sorted((REPO_ROOT / "schemas").glob("*.schema.json")) ] @@ -55,7 +56,7 @@ def _schema_field_rows(schema: dict, keys: tuple[str, ...]) -> list[str]: text = str((props.get(key) or {}).get("description") or "") if text: # Python before 3.12 refuses a backslash inside an f-string expression. - described = _escape_tags(_URL_TEMPLATE.sub(r"`\g<0>`", text)) + described = escape_tags(_URL_TEMPLATE.sub(r"`\g<0>`", text)) rows.append(f"| `{key}` | {described} |") return rows @@ -132,8 +133,8 @@ def _join_names(names: list[str]) -> str: def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = None) -> str: manifest_schema = json.loads( - (_REPO_ROOT / "schemas" / "install-manifest.schema.json").read_text(encoding="utf-8")) - snippet = (_REPO_ROOT / "scripts" / "check_platform_folder.py").read_text(encoding="utf-8") + (REPO_ROOT / "schemas" / "install-manifest.schema.json").read_text(encoding="utf-8")) + snippet = (REPO_ROOT / "scripts" / "check_platform_folder.py").read_text(encoding="utf-8") manifests = [item for item in exports if _is_manifest(item)] targets = [item for item in exports if _is_target_list(item)] no_list = _platforms_without_a_list() @@ -177,7 +178,7 @@ def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = N ) lines.append( f"| {item['title']} | [`{item['url']}`]({item['url']}) | " - f"{schema} | {_fmt_size(item['bytes'])} |" + f"{schema} | {fmt_size(item['bytes'])} |" ) lines.extend([ "", @@ -353,7 +354,7 @@ def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = N continue lines.append( f"| [{item['title']}]({item['url']}) | `{item['media_type']}` | " - f"{_fmt_size(item['bytes'])} | {_short_sha256(item, 'api/v1/catalog.json')} |" + f"{fmt_size(item['bytes'])} | {_short_sha256(item, 'api/v1/catalog.json')} |" ) lines.extend([ "", diff --git a/scripts/sitegen/decorate.py b/scripts/sitegen/decorate.py index 81c81e3e7..52498fa62 100644 --- a/scripts/sitegen/decorate.py +++ b/scripts/sitegen/decorate.py @@ -12,11 +12,12 @@ from model import releaserecord from model import siteinputs from model.database import load_database from sitegen import markup, measurements as sitemeasurements, starlight as sitestarlight -from sitegen.config import SITE_NAME, SITE_URL, _REPO_ROOT, yaml -from sitegen.descriptions import PAGE_DATA, _browser_title, _page_description, _page_title +from sitegen.config import SITE_NAME, SITE_URL, yaml +from core.paths import REPO_ROOT +from sitegen.descriptions import PAGE_DATA, page_browser_title, page_description, page_title from sitegen.diagrams import prepare_page, unresolved_images from sitegen.render import WIKI_SRC_DIR -from sitegen.write import _undecorated, write_decorated +from sitegen.write import undecorated, write_decorated # Working notes kept under docs/ during development, never part of the site, @@ -99,7 +100,7 @@ def level_label(level: str) -> str: return f'{LEVELS[level]}' -def _front_matter(markdown: str) -> dict: +def front_matter(markdown: str) -> dict: """The YAML front matter of a page, empty when it has none.""" if not markdown.startswith("---\n"): return {} @@ -138,13 +139,13 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]: returned by address, for the sitemap. """ lastmod: dict[str, str] = {} - terms = sitestarlight.glossary_terms(_REPO_ROOT / WIKI_SRC_DIR / "glossary.md") + terms = sitestarlight.glossary_terms(REPO_ROOT / WIKI_SRC_DIR / "glossary.md") # The console words of every system page, decorated or not: a console # another page's words cover gets a search field of its own. console_words: dict[str, set[str]] = {} for path in sorted((docs / "systems").glob("*.md*")): text = path.read_text(encoding="utf-8") - words = sitestarlight.page_console_words(_front_matter(text), text) + words = sitestarlight.page_console_words(front_matter(text), text) if words: console_words[path.relative_to(docs).with_suffix("").as_posix()] = words for path in sorted(docs.rglob("*.md")): @@ -152,7 +153,7 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]: if any(part in LOCAL_NOTE_DIRS for part in relative.parts[:-1]): continue original = path.read_text(encoding="utf-8") - authored = _front_matter(original) + authored = front_matter(original) if "head" in authored: # Written in its final form by an earlier pass and rewritten by # nothing since: a second pass would find no title to read. @@ -160,7 +161,7 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]: markdown = _cards_elsewhere(prepare_page(original, relative)) for image_id in unresolved_images(markdown): print(f" WARNING: {relative}: no diagram named {image_id!r}", file=sys.stderr) - stripped = _undecorated(markdown) + stripped = undecorated(markdown) if stripped is not markdown: markdown = stripped elif authored: @@ -168,9 +169,9 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]: markdown = markdown[markdown.find("\n---\n", 4) + 5:].lstrip("\n") level = authored.get("level") or page_level(relative) - title = _page_title(markdown, relative) - browser_title = _browser_title(relative, title) - description = str(authored.get("description") or _page_description(markdown, relative, title)) + title = page_title(markdown, relative) + browser_title = page_browser_title(relative, title) + description = str(authored.get("description") or page_description(markdown, relative, title)) if relative.name == "index.md": page_path = "" if len(relative.parts) == 1 else "/".join(relative.parts[:-1]) + "/" else: diff --git a/scripts/sitegen/descriptions.py b/scripts/sitegen/descriptions.py index 30a7311b0..fb77a79e5 100644 --- a/scripts/sitegen/descriptions.py +++ b/scripts/sitegen/descriptions.py @@ -11,7 +11,7 @@ from sitegen import measurements as sitemeasurements from sitegen.config import SITE_NAME -def _page_title(markdown: str, path: Path) -> str: +def page_title(markdown: str, path: Path) -> str: match = re.search(r"^#\s+(.+?)\s*$", markdown, flags=re.MULTILINE) if match: title = re.sub(r"<[^>]+>", "", match.group(1)) @@ -19,7 +19,7 @@ def _page_title(markdown: str, path: Path) -> str: return path.stem.replace("-", " ").title() -def _browser_title(relative: Path, title: str) -> str: +def page_browser_title(relative: Path, title: str) -> str: """Return a concise, unique browser/search title for a generated page.""" key = relative.as_posix() index_titles = { @@ -84,7 +84,7 @@ def _shorten(plain: str, limit: int = 157) -> str: return cut.rstrip(" ,;:-(.") + "..." -def _page_description(markdown: str, relative: Path, title: str) -> str: +def page_description(markdown: str, relative: Path, title: str) -> str: key = relative.as_posix() specific = { "index.md": "The BIOS files emulators need, for RetroArch, Batocera, EmuDeck and more: the folder they go in, one command that installs and checks them, and packs to download.", @@ -103,7 +103,7 @@ def _page_description(markdown: str, relative: Path, title: str) -> str: return specific[key] # What a search engine shows is the page's own first sentence: 707 pages # shared five templates of level 3 words ("source-pinned", "provenance"). - browser = _browser_title(relative, title) + browser = page_browser_title(relative, title) held = re.search(r"\bThis part holds (.+?)\.(?: |$)", markdown, re.M) if key in PART_PAGES and held: return _shorten(f"{browser}. This part holds {_plain_markdown(held[1])}.", 155) @@ -226,7 +226,7 @@ def _files_snippet(markdown: str, key: str, title: str, intro: str) -> str: for count in range(min(len(names), 4), 0, -1): shown = (names if count == len(names) else [*names[:count - 1], f"{len(names) - count + 1:,} more"]) - head = f"{subject}: {_said_as_list(shown)}, {need}." + head = f"{subject}: {said_as_list(shown)}, {need}." forms += [f"{head} {tail}" for tail in tails if tail] + [head] return next((form for form in forms if len(form) <= 155), intro) @@ -271,7 +271,7 @@ def _system_description(markdown: str, browser: str) -> str: consoles = [name for name in consoles if name and name not in _NOT_A_CONSOLE] if len(consoles) > 1: shown = consoles if len(consoles) <= 4 else consoles[:3] + [f"{len(consoles) - 3} more"] - return _shorten(f"{browser} for {_said_as_list(shown)}, one card per file with its " + return _shorten(f"{browser} for {said_as_list(shown)}, one card per file with its " "hashes and the emulators that read it.", 155) start = re.search(r"^\*\*Start with\*\*(?P.*)$(?P(?:\n+- .*)*)", markdown, re.M) if start: @@ -283,7 +283,7 @@ def _system_description(markdown: str, browser: str) -> str: names = list(dict.fromkeys(html.unescape(name) for name in _CARD_TITLE.findall(markdown))) if names: shown = names if len(names) <= 3 else names[:3] + [f"{len(names) - 3} more"] - return _shorten(f"{browser}: {_said_as_list(shown)}, with their hashes and the " + return _shorten(f"{browser}: {said_as_list(shown)}, with their hashes and the " "emulators that read them.", 155) return _shorten(f"{browser}, one card per file with its hashes and the emulators " "that read it.", 155) @@ -304,6 +304,6 @@ EMULATOR_SNIPPETS: dict[str, tuple[str, list[str], int, str]] = {} PART_PAGES: set[str] = set() -def _said_as_list(items: list[str]) -> str: +def said_as_list(items: list[str]) -> str: """"a, b and c".""" return ", ".join(items[:-1]) + f" and {items[-1]}" if len(items) > 1 else "".join(items) diff --git a/scripts/sitegen/diagrams.py b/scripts/sitegen/diagrams.py index 14c8805ca..4f6cdc1c7 100644 --- a/scripts/sitegen/diagrams.py +++ b/scripts/sitegen/diagrams.py @@ -18,8 +18,6 @@ from model import siteinputs from sitegen import markup -ROOT = REPO_ROOT - PLACEHOLDER = re.compile(r"(?m)^([ \t]*)[ \t]*$") PLACEHOLDER_ANYWHERE = re.compile(r"") @@ -76,7 +74,7 @@ def wrap(text: str, width: float, size: float, bold: bool = False) -> list[str]: return lines -def _n(value: float) -> str: +def svg_number(value: float) -> str: text = f"{value:.1f}" return text[:-2] if text.endswith(".0") else text @@ -104,48 +102,48 @@ class Figure: # Drawing primitives -def _text(x: float, y: float, value: str, size: float = TEXT_SIZE, +def svg_text(x: float, y: float, value: str, size: float = TEXT_SIZE, bold: bool = False, anchor: str = "start", cls: str = "") -> str: weight = ' font-weight="600"' if bold else "" klass = f' class="{cls}"' if cls else "" style = f' style="{MONO_STYLE}"' if isinstance(value, Mono) else "" fill = MUTED if cls == "rb-d-muted" else ("#ffffff" if cls == "rb-d-numtext" else INK) return ( - f'{escape(value)}' ) -def _rect(x: float, y: float, w: float, h: float, accent: bool = False) -> str: +def svg_rect(x: float, y: float, w: float, h: float, accent: bool = False) -> str: cls = "rb-d-box rb-d-accent" if accent else "rb-d-box" stroke = ACCENT if accent else STROKE width = 2 if accent else 1 return ( - f'' ) -def _badge_side(number: str) -> float: +def badge_side(number: str) -> float: return max(20.0, _width(number, 11, True) + 10) -def _badge(x: float, y: float, number: str) -> list[str]: - side = _badge_side(number) +def badge(x: float, y: float, number: str) -> list[str]: + side = badge_side(number) return [ - f'', - _text(x + side / 2, y + 14, number, 11, True, "middle", "rb-d-numtext"), + svg_text(x + side / 2, y + 14, number, 11, True, "middle", "rb-d-numtext"), ] -def _line(points: list[tuple[float, float]], head: bool = True) -> list[str]: +def svg_connector(points: list[tuple[float, float]], head: bool = True) -> list[str]: """A connector through *points*, with a drawn arrowhead at the end. The head is a small triangle, never a text glyph. """ path = " ".join( - f"{'M' if index == 0 else 'L'}{_n(x)} {_n(y)}" for index, (x, y) in enumerate(points) + f"{'M' if index == 0 else 'L'}{svg_number(x)} {svg_number(y)}" for index, (x, y) in enumerate(points) ) out = [ f'' @@ -159,7 +157,7 @@ def _line(points: list[tuple[float, float]], head: bool = True) -> list[str]: sign = 1 if x2 > x1 else -1 tri = [(x2, y2), (x2 - 8 * sign, y2 - 5), (x2 - 8 * sign, y2 + 5)] out.append( - '' ) return out @@ -168,7 +166,7 @@ def _line(points: list[tuple[float, float]], head: bool = True) -> list[str]: def box_lines(box: Box, width: float) -> tuple[list[str], list[str]]: """The title and body lines of *box* drawn *width* wide, as wrapped.""" inner = width - 2 * PAD - title_lines = wrap(box.title, inner - (_badge_side(box.number) + 8 if box.number else 0), + title_lines = wrap(box.title, inner - (badge_side(box.number) + 8 if box.number else 0), TITLE_SIZE, True) body: list[str] = [] for line in box.lines: @@ -186,18 +184,18 @@ def _box_height(box: Box, width: float) -> tuple[list[str], list[str], float]: def _draw_box(box: Box, x: float, y: float, width: float, height: float, title_lines: list[str], body: list[str]) -> list[str]: - out = [_rect(x, y, width, height, box.accent)] + out = [svg_rect(x, y, width, height, box.accent)] tx = x + PAD if box.number: - out.extend(_badge(x + PAD, y + PAD, box.number)) - tx += _badge_side(box.number) + 8 + out.extend(badge(x + PAD, y + PAD, box.number)) + tx += badge_side(box.number) + 8 cy = y + PAD + 15 for line in title_lines: - out.append(_text(tx, cy, line, TITLE_SIZE, True)) + out.append(svg_text(tx, cy, line, TITLE_SIZE, True)) cy += LINE cy += 6 for line in body: - out.append(_text(x + PAD, cy, line, TEXT_SIZE, cls="rb-d-muted")) + out.append(svg_text(x + PAD, cy, line, TEXT_SIZE, cls="rb-d-muted")) cy += LINE return out @@ -214,7 +212,7 @@ def flow(boxes: list[Box], vertical: bool, total: float) -> tuple[float, float, out.extend(_draw_box(box, 1, y, width - 2, height, title_lines, body)) y += height if index < len(boxes) - 1: - out.extend(_line([(width / 2, y), (width / 2, y + 22)])) + out.extend(svg_connector([(width / 2, y), (width / 2, y + 22)])) y += 24 return width, y + 1, out gap = 26.0 @@ -228,7 +226,7 @@ def flow(boxes: list[Box], vertical: bool, total: float) -> tuple[float, float, out.extend(_draw_box(box, x, 1, width, height, title_lines, body)) if index < len(boxes) - 1: mid = 1 + height / 2 - out.extend(_line([(x + width, mid), (x + width + gap - 1, mid)])) + out.extend(svg_connector([(x + width, mid), (x + width + gap - 1, mid)])) return total, height + 2, out @@ -267,11 +265,11 @@ def grid(boxes: list[Box], per_row: int, total: float) -> tuple[float, float, li x = 1 + index * (width + gap_x) if previous_end is not None and index == 0: px, py = previous_end - out.extend(_line([(px, py), (px, py + gap_y / 2), (x + width / 2, py + gap_y / 2), + out.extend(svg_connector([(px, py), (px, py + gap_y / 2), (x + width / 2, py + gap_y / 2), (x + width / 2, y)])) out.extend(_draw_box(box, x, y, width, height, title_lines, body)) if index < len(row) - 1: - out.extend(_line([(x + width, y + height / 2), (x + width + gap_x - 1, y + height / 2)])) + out.extend(svg_connector([(x + width, y + height / 2), (x + width + gap_x - 1, y + height / 2)])) previous_end = (x + width / 2, y + height) y += height + gap_y return total, y - gap_y + 1, out @@ -281,8 +279,8 @@ def svg_document(width: float, height: float, title: str, desc: str, body: list[ base: str) -> str: """A drawing as a standalone, accessible SVG element.""" return ( - f'' f'{escape(title)}' f'{escape(desc)}' @@ -539,7 +537,7 @@ MINUI_EXAMPLES = (("Sony PlayStation", "PS"), ("Game Boy Advance", "GBA"), ("Seg @cache def minui_files() -> dict[str, list[str]]: - manifest = json.loads((ROOT / "install" / "minui.json").read_text(encoding="utf-8")) + manifest = json.loads((REPO_ROOT / "install" / "minui.json").read_text(encoding="utf-8")) by_tag: dict[str, list[str]] = {} for entry in manifest.get("files", []): parts = str(entry.get("dest", "")).split("/") @@ -551,23 +549,23 @@ def minui_files() -> dict[str, list[str]]: def _minui_wide() -> tuple[float, float, list[str]]: out: list[str] = [] left_x, right_x, row = 1.0, 430.0, 22.0 - out.append(_text(left_x, 16, "Roms/", TITLE_SIZE, True)) - out.append(_text(right_x, 16, "Bios/", TITLE_SIZE, True)) + out.append(svg_text(left_x, 16, "Roms/", TITLE_SIZE, True)) + out.append(svg_text(right_x, 16, "Bios/", TITLE_SIZE, True)) y = 30.0 for name, tag in MINUI_EXAMPLES: files = minui_files().get(tag, []) shown = files[:2] + ([f"and {len(files) - 2} more"] if len(files) > 2 else []) height = max(row + 8, 14 + row * (1 + len(shown))) label = f"{name} ({tag})/" - out.append(_rect(left_x + 14, y, 250, row + 8)) - out.append(_text(left_x + 24, y + 19, label, TEXT_SIZE, True)) - out.append(_rect(right_x + 14, y, 250, height)) - out.append(_text(right_x + 24, y + 19, f"{tag}/", TEXT_SIZE, True)) + out.append(svg_rect(left_x + 14, y, 250, row + 8)) + out.append(svg_text(left_x + 24, y + 19, label, TEXT_SIZE, True)) + out.append(svg_rect(right_x + 14, y, 250, height)) + out.append(svg_text(right_x + 24, y + 19, f"{tag}/", TEXT_SIZE, True)) for index, file_name in enumerate(shown): - out.append(_text(right_x + 40, y + 19 + row * (index + 1), file_name, TEXT_SIZE, + out.append(svg_text(right_x + 40, y + 19 + row * (index + 1), file_name, TEXT_SIZE, cls="rb-d-muted")) - out.extend(_line([(left_x + 264, y + (row + 8) / 2), (right_x + 13, y + (row + 8) / 2)])) - out.append(_text((left_x + 264 + right_x + 14) / 2, y + (row + 8) / 2 - 6, + out.extend(svg_connector([(left_x + 264, y + (row + 8) / 2), (right_x + 13, y + (row + 8) / 2)])) + out.append(svg_text((left_x + 264 + right_x + 14) / 2, y + (row + 8) / 2 - 6, f"tag {tag}", 11, anchor="middle", cls="rb-d-muted")) y += height + 14 return WIDE, y - 12, out @@ -578,10 +576,10 @@ def _minui_narrow() -> tuple[float, float, list[str]]: y = 1.0 for name, tag in MINUI_EXAMPLES: files = minui_files().get(tag, []) - out.append(_rect(1, y, NARROW - 2, 30)) - out.append(_text(11, y + 20, f"Roms/{name} ({tag})/", TEXT_SIZE, True)) - out.extend(_line([(NARROW / 2, y + 30), (NARROW / 2, y + 52)])) - out.append(_text(NARROW / 2 + 10, y + 45, f"tag {tag}", 11, cls="rb-d-muted")) + out.append(svg_rect(1, y, NARROW - 2, 30)) + out.append(svg_text(11, y + 20, f"Roms/{name} ({tag})/", TEXT_SIZE, True)) + out.extend(svg_connector([(NARROW / 2, y + 30), (NARROW / 2, y + 52)])) + out.append(svg_text(NARROW / 2 + 10, y + 45, f"tag {tag}", 11, cls="rb-d-muted")) y += 54 detail = "" if len(files) == 1: @@ -589,17 +587,17 @@ def _minui_narrow() -> tuple[float, float, list[str]]: elif files: detail = f"{len(files)} files, such as {files[0]}" height = 30 + (LINE if detail else 0) - out.append(_rect(1, y, NARROW - 2, height, accent=True)) - out.append(_text(11, y + 20, f"Bios/{tag}/", TEXT_SIZE, True)) + out.append(svg_rect(1, y, NARROW - 2, height, accent=True)) + out.append(svg_text(11, y + 20, f"Bios/{tag}/", TEXT_SIZE, True)) if detail: - out.append(_text(11, y + 20 + LINE, detail, TEXT_SIZE, cls="rb-d-muted")) + out.append(svg_text(11, y + 20 + LINE, detail, TEXT_SIZE, cls="rb-d-muted")) y += height + 18 return NARROW, y - 17, out def _pipeline_boxes() -> list[Box]: """The steps pipeline.py runs, read from its STEP_LABELS literal.""" - tree = ast.parse((ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8")) + tree = ast.parse((REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8")) for node in ast.walk(tree): if isinstance(node, ast.Assign): target: ast.expr = node.targets[0] @@ -638,15 +636,15 @@ def _layers(vertical: bool) -> tuple[float, float, list[str]]: px, py, pw, ph = place(platform, 1, 1, 200) sx, sy, sw, sh = place(shared, 1, py + ph + 26, 200) ex, ey, ew, eh = place(profiles, 1, sy + sh + 26, 200) - out.extend(_line([(sx + sw / 2, sy), (px + pw / 2, py + ph)])) - out.extend(_line([(sx + sw / 2, sy + sh), (ex + ew / 2, ey)])) + out.extend(svg_connector([(sx + sw / 2, sy), (px + pw / 2, py + ph)])) + out.extend(svg_connector([(sx + sw / 2, sy + sh), (ex + ew / 2, ey)])) _, _, pack_h = _box_height(pack, 200) gx, gy, gw, gh = place(pack, 270, sy + (sh - pack_h) / 2, 200) - out.extend(_line([(px + pw, py + ph / 2), (240, py + ph / 2), (240, gy + 20), (gx - 1, gy + 20)])) - out.extend(_line([(ex + ew, ey + eh / 2), (240, ey + eh / 2), (240, gy + gh - 20), + out.extend(svg_connector([(px + pw, py + ph / 2), (240, py + ph / 2), (240, gy + 20), (gx - 1, gy + 20)])) + out.extend(svg_connector([(ex + ew, ey + eh / 2), (240, ey + eh / 2), (240, gy + gh - 20), (gx - 1, gy + gh - 20)])) zx, zy, zw, zh = place(zip_box, 518, gy + (gh - 42) / 2, 200) - out.extend(_line([(gx + gw, gy + gh / 2), (zx - 1, gy + gh / 2)])) + out.extend(svg_connector([(gx + gw, gy + gh / 2), (zx - 1, gy + gh / 2)])) return WIDE, max(ey + eh, gy + gh) + 2, out w = NARROW - 2 @@ -654,14 +652,14 @@ def _layers(vertical: bool) -> tuple[float, float, list[str]]: sx, sy, sw, sh = place(shared, 1, 1, w) px, py, pw, ph = place(platform, 1, sy + sh + 26, half) ex, ey, ew, eh = place(profiles, 15 + half, py, half) - out.extend(_line([(px + pw / 2, sy + sh), (px + pw / 2, py)])) - out.extend(_line([(ex + ew / 2, sy + sh), (ex + ew / 2, ey)])) + out.extend(svg_connector([(px + pw / 2, sy + sh), (px + pw / 2, py)])) + out.extend(svg_connector([(ex + ew / 2, sy + sh), (ex + ew / 2, ey)])) bottom = max(py + ph, ey + eh) gx, gy, gw, gh = place(pack, 1, bottom + 26, w) - out.extend(_line([(px + pw / 2, py + ph), (px + pw / 2, gy)])) - out.extend(_line([(ex + ew / 2, ey + eh), (ex + ew / 2, gy)])) + out.extend(svg_connector([(px + pw / 2, py + ph), (px + pw / 2, gy)])) + out.extend(svg_connector([(ex + ew / 2, ey + eh), (ex + ew / 2, gy)])) zx, zy, zw, zh = place(zip_box, 1, gy + gh + 26, w) - out.extend(_line([(NARROW / 2, gy + gh), (NARROW / 2, zy)])) + out.extend(svg_connector([(NARROW / 2, gy + gh), (NARROW / 2, zy)])) return NARROW, zy + zh + 2, out @@ -791,8 +789,8 @@ def unresolved_images(markdown: str) -> list[str]: # Local copies of images the site used to load from other hosts. -LOGO_DIR = ROOT / "docs_assets" / "logos" -ICON_DIR = ROOT / "docs_assets" / "system-icons" +LOGO_DIR = REPO_ROOT / "docs_assets" / "logos" +ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons" SITE_LOGO_DIR = "assets/logos" SITE_ICON_DIR = "assets/system-icons" IMAGE_LINK = re.compile(r"(!\[[^\]\n]*\]\()(https?://[^)\s]+)(\))") @@ -912,7 +910,7 @@ def _string(node: ast.expr, constants: dict[str, str]) -> str: @cache def installer_options() -> tuple[tuple[str, str], ...]: """(usage, help) for each option of install.py, in the order --help lists them.""" - tree = ast.parse((ROOT / "install.py").read_text(encoding="utf-8")) + tree = ast.parse((REPO_ROOT / "install.py").read_text(encoding="utf-8")) constants = { node.targets[0].id: node.value.value for node in tree.body diff --git a/scripts/sitegen/emulatorcards.py b/scripts/sitegen/emulatorcards.py index a719e9068..4ad1a8672 100644 --- a/scripts/sitegen/emulatorcards.py +++ b/scripts/sitegen/emulatorcards.py @@ -10,7 +10,7 @@ from collections.abc import Callable, Iterable from dataclasses import dataclass from pathlib import Path -from model.collection import _slug +from model.collection import manufacturer_slug from model.systemnames import system_name from packs.crossref import FileConsumers, entry_target, held_copy from resolve.cores import resolve_platform_cores @@ -19,37 +19,37 @@ from sitegen.cards import ( ROMSET_FAQ, SEARCH_SKIPPED, SHORT_HASH, - _card_title, - _listed_words, - _places_markdown, - _platform_links, - _platform_places, - _search_skipped_apart, + card_title, + listed_words, + places_markdown, + platform_links, + platform_places, + search_skipped_apart, card_fold, ) from sitegen.config import REPO_URL -from sitegen.descriptions import _said_as_list -from sitegen.fields import _hash_spans +from sitegen.descriptions import said_as_list +from sitegen.fields import hash_spans from sitegen.install import ( - _OS_LABELS, - _platform_display, - _under_root, + OS_LABELS, + platform_display, + under_root, comes_with_app, data_root_words, standalone_place, ) from sitegen.render import ( WIKI_SRC_DIR, - _code, - _count, - _escape_tags, - _fmt_size, + code_span, + count_text, + escape_tags, + fmt_size, card_page, console_href, ) from sitegen.sources import ( - _source_permalink, - _source_ref_markdown, + source_permalink, + source_ref_markdown, link_prose_citations, requested_by, version_basis_url, @@ -59,7 +59,7 @@ from sitegen.sources import ( # Emulator pages -def _named_system_link(sys_id: str, prefix: str = "") -> str: +def named_system_link(sys_id: str, prefix: str = "") -> str: """A system by its display name, linked where _system_link links it. The emulator pages printed the id ("sony-playstation") where every @@ -79,7 +79,7 @@ def _named_system_link(sys_id: str, prefix: str = "") -> str: _REGION_WORDS = {"world": "every region"} -def _region_words(value: object, most: int = 0) -> str: +def region_words(value: object, most: int = 0) -> str: """A region: value in words. ``most`` caps the regions named, the rest counted: one Saturn BIOS serves seven.""" raw = value if isinstance(value, list) else [value] if value else [] @@ -88,13 +88,13 @@ def _region_words(value: object, most: int = 0) -> str: words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw] if most and len(words) > most: words = words[:most] + [f"{len(words) - most} more"] - return _said_as_list(words) + return said_as_list(words) _CATEGORY_WORDS = {"bios": "BIOS", "game_data": "game data", "bios_zip": "BIOS ZIP"} -def _snippet_noun(names: Iterable[str], firmware: int, fetched: int) -> str: +def snippet_noun(names: Iterable[str], firmware: int, fetched: int) -> str: """What an emulator's files are called in its snippet. A Switch emulator reads keys, and "eden keys" is what readers search for. Ship of Harkinian reads game ROMs, which are no BIOS.""" @@ -142,7 +142,7 @@ def _status_badges(f: dict, in_repo: bool, for_system: str, shipped: bool) -> li return badges -def _file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]: +def file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]: """The status chips shown beside a file name. Fourteen independent optional fields, each contributing at most one @@ -176,7 +176,7 @@ def _file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]: if region: # Labelled: "optional in repo japan" read as one run-on phrase. badges.append( - f'Region: {_region_words(region)}' + f'Region: {region_words(region)}' ) if storage and storage != "embedded": badges.append( @@ -228,7 +228,7 @@ def _load_from_text(value: object) -> str: """ if value in (None, "", "system_dir"): return "" - return _by_build(value, lambda v: _LOAD_FROM.get(v, _code(v))) + return _by_build(value, lambda v: _LOAD_FROM.get(v, code_span(v))) def _found_by_text(value: object) -> str: @@ -238,7 +238,7 @@ def _found_by_text(value: object) -> str: "content": "content (the code scans the folder and identifies the file " "by its hash, any file name works)", } - return _by_build(value, lambda v: words.get(v, _code(v))) + return _by_build(value, lambda v: words.get(v, code_span(v))) def _on_mismatch_lines(value: object) -> list[str]: @@ -247,7 +247,7 @@ def _on_mismatch_lines(value: object) -> list[str]: if value == "warn": return [f"On a failed check: {said['warn']}"] if isinstance(value, dict): - return [f"On a failed {check} check: {said.get(str(how), _code(str(how)))}" + return [f"On a failed {check} check: {said.get(str(how), code_span(str(how)))}" for check, how in value.items()] return [] @@ -259,7 +259,7 @@ def emulator_setups(coverages: dict, profiles: dict) -> dict[str, list[str]]: for emulator in resolve_platform_cores(cov["config"], profiles): setups.setdefault(emulator, []).append(platform) return { - emulator: sorted(names, key=lambda p: _platform_display(p).casefold()) + emulator: sorted(names, key=lambda p: platform_display(p).casefold()) for emulator, names in setups.items() } @@ -273,30 +273,30 @@ def _validation_names(validation: dict | list | None) -> set[str]: def _exact_size(size: int) -> str: """A rounded size with its bytes, where the bytes are not the same figure.""" - return _fmt_size(size) if size < 1024 else f"{_fmt_size(size)} ({size:,} bytes)" + return fmt_size(size) if size < 1024 else f"{fmt_size(size)} ({size:,} bytes)" def _build_file_links(pin_build: list[dict]) -> list[str]: """Each platform build file that holds the revision, linked at the commit it was read at when the source record holds it. The prose of pin_frozen named the file as plain text.""" - from sitegen.sources import _browse_repo, tree_holds + from sitegen.sources import browse_repo, tree_holds links = [] for build in pin_build: - repo = _browse_repo(str(build["repo"])) + repo = browse_repo(str(build["repo"])) path = str(build["path"]) revision = str(build["revision"]) - text = f"{_escape_tags(_platform_display(str(build['platform'])))} {_code(path)}" + text = f"{escape_tags(platform_display(str(build['platform'])))} {code_span(path)}" # Linked where the record saw the file at that commit, as every # source link is: a tag can move, and is never recorded. if repo is not None and tree_holds(repo, revision, path): - text = f"[{text}]({_source_permalink(repo, revision, path, None, None)})" - links.append(f"{text} at {_code(str(build['revision']))} sets {_code(str(build['variable']))}") + text = f"[{text}]({source_permalink(repo, revision, path, None, None)})" + links.append(f"{text} at {code_span(str(build['revision']))} sets {code_span(str(build['variable']))}") return links -def _build_rows(profile: dict) -> list[str]: +def build_rows(profile: dict) -> list[str]: """Meta card rows for who ships the build, how its files are found, why its revision is held and where its releases are announced.""" rows = [] @@ -314,7 +314,7 @@ def _build_rows(profile: dict) -> list[str]: ("upstream_frozen", "Upstream revision held")): frozen = profile.get(field) if frozen: - held = _escape_tags(' '.join(str(frozen).split())).replace('|', r'\|') + held = escape_tags(' '.join(str(frozen).split())).replace('|', r'\|') rows.append(f"| {label} | {held} |") builds = _build_file_links(profile.get("pin_build") or []) if builds: @@ -324,21 +324,21 @@ def _build_rows(profile: dict) -> list[str]: url = str(announced["url"]) row = f"| Releases announced at | [{url}]({url})" if announced.get("no_genuine_copy"): - row += (f" (version {_escape_tags(str(announced['no_genuine_copy']))} " + row += (f" (version {escape_tags(str(announced['no_genuine_copy']))} " "announced there, found only as rebuilt copies)") rows.append(row + " |") return rows -def _entry_label(f: dict, profile: dict) -> str: +def entry_label(f: dict, profile: dict) -> str: """The name a file card goes by, its title without the badges.""" fname = f.get("name", "") if f is any_name_bios(profile): # Found by content: the name is an example, any image of the system works. system = system_name((profile.get("systems") or [""])[0]) - return (f"a {system} BIOS (example: {_code(fname)})" if _named_example(str(fname)) + return (f"a {system} BIOS (example: {code_span(fname)})" if named_example(str(fname)) else f"a {system} BIOS, any file name") - return _code(fname) + return code_span(fname) @dataclass(frozen=True) @@ -382,7 +382,7 @@ def _card_place_details(f: dict, profile: dict, owner: str, data_href: str) -> l if found: details.append(f"Found by: {found}") if fsystem: - details.append(f"System: {_named_system_link(fsystem, '../')}") + details.append(f"System: {named_system_link(fsystem, '../')}") return details @@ -393,7 +393,7 @@ def _card_size_details(f: dict) -> list[str]: fmax = f.get("max_size") # Where the code compares the size, the exact bytes: raze tells three # DUKE3D.GRP apart by size, all three shown as 42.3 MB. - sized = _exact_size if "size" in _validation_names(f.get("validation", [])) else _fmt_size + sized = _exact_size if "size" in _validation_names(f.get("validation", [])) else fmt_size bounds = [] if fmin: bounds.append(f"min {sized(fmin)}") @@ -423,22 +423,22 @@ def _card_hash_details(f: dict) -> list[str]: # Starlight folds the hashes and gives each a copy button. copyable = markup.starlight() if fsha1: - details.append(f"SHA1: {_hash_spans(fsha1, copyable)}") + details.append(f"SHA1: {hash_spans(fsha1, copyable)}") if fmd5: - details.append(f"MD5: {_hash_spans(fmd5, copyable)}") + details.append(f"MD5: {hash_spans(fmd5, copyable)}") if fcrc32: crcs = fcrc32 if isinstance(fcrc32, list) else [fcrc32] details.append("CRC32: " + ", ".join( markup.hash_value(crc, True) if copyable else f"`{crc}`" for crc in crcs)) if fsha256: - details.append(f"SHA256: {_hash_spans(fsha256, copyable)}") + details.append(f"SHA256: {hash_spans(fsha256, copyable)}") if fadler32: # Printed as the downloads spell a hash, one per code span: the list # repr read `['0x66f334fe', ...]`. Dolphin hashes its DSP ROMs over # byte-swapped 16-bit words, so the raw Adler-32 the downloads carry # for the same file differs, and the card says which one it lists. values = fadler32 if isinstance(fadler32, list) else [fadler32] - shown = ", ".join(_code(str(v).lower().removeprefix("0x")) for v in values) + shown = ", ".join(code_span(str(v).lower().removeprefix("0x")) for v in values) if f.get("adler32_byteswap"): details.append( f"Adler32 over the file's 16-bit words byte-swapped: {shown} " @@ -492,7 +492,7 @@ def _card_reading_details(f: dict, profile: dict) -> list[str]: # for the file. details.append(f"Asked for by: {asker}") details.append( - f"Source: {_source_ref_markdown(profile, source_ref)}" + f"Source: {source_ref_markdown(profile, source_ref)}" ) return details @@ -511,7 +511,7 @@ def _card_copy_line( # said "in repo" without naming the file. page = card_page(held, sha1) return [ - f"Collection copy: [{_code(held)}]" + f"Collection copy: [{code_span(held)}]" f"(../systems/{urllib.parse.quote(page)}.md#sha1-{sha1[:12]})" ] if in_repo and not any(d.startswith("Collection copies:") for d in details): @@ -536,13 +536,13 @@ def _card_copy_details( *entry_target(f, profile.get("files") or []), owner=owner) held = consumers.path_of(sha1) if sha1 and in_repo else "" added.extend(_card_copy_line(f, consumers, held, sha1, in_repo, details + added)) - plat_links = _platform_links(sha1, consumers) if sha1 else [] + plat_links = platform_links(sha1, consumers) if sha1 else [] if plat_links and markup.starlight(): # Grouped by where the setups put the file, as the system card # says it: twelve setups repeating scph5502.bin took twelve # names and twelve paths where a few say it. One sentence a # place: a list or a line break was one more element a place. - places = _places_markdown(_platform_places(sha1, consumers)) + places = places_markdown(platform_places(sha1, consumers)) added.append("Platforms: " + ". ".join(places)) elif plat_links: added.append(f"Platforms: {', '.join(plat_links)}") @@ -584,21 +584,21 @@ def _card_heading(f: dict, profile: dict, in_repo: bool, anchor: str, layout: Ca # above the DS files, for an emulator most people run for DS games. for_system = (system_name(str(fsystem)) if fsystem and len(profile.get("systems") or []) > 1 else "") - badges = _file_badges(f, in_repo, for_system) + badges = file_badges(f, in_repo, for_system) badge_str = " ".join(badges) lines.append(markup.block_open("div", 'class="rb-file-entry"')) lines.append("") marker = f'' if layout.alias else "" - label = _entry_label(f, profile) + label = entry_label(f, profile) title = f"{marker}{label}" if layout.badges_apart else f"{marker}{label} {badge_str}" - lines.append(_card_title(title, anchor, weight=5)) + lines.append(card_title(title, anchor, weight=5)) lines.append("") if desc: - lines.extend([data_root_words(_escape_tags(str(desc)), layout.data_href), ""]) + lines.extend([data_root_words(escape_tags(str(desc)), layout.data_href), ""]) return lines -def _render_emulator_file( +def render_emulator_file( f: dict, profile: dict, consumers: FileConsumers | None, @@ -639,11 +639,11 @@ def _render_emulator_file( return lines lines.extend(f"- {d}" for d in details) if fnote: - lines.append(f"- {data_root_words(_escape_tags(link_prose_citations(profile, str(fnote))), data_href)}") + lines.append(f"- {data_root_words(escape_tags(link_prose_citations(profile, str(fnote))), data_href)}") if not in_repo and f.get("unsourceable"): lines.append(f"- {_unsourceable_line(f)}") lines.extend(_contents_lines(contents)) - lines[body_start:] = _search_skipped_apart(lines[body_start:]) + lines[body_start:] = search_skipped_apart(lines[body_start:]) lines.append("") lines.append("") lines.append("") @@ -661,9 +661,9 @@ def _contents_lines(contents: list) -> list[str]: if isinstance(c, dict): parts = [] if c.get("description"): - parts.append(_escape_tags(str(c["description"]))) + parts.append(escape_tags(str(c["description"]))) if c.get("size"): - parts.append(_fmt_size(c["size"])) + parts.append(fmt_size(c["size"])) if c.get("crc32"): parts.append(f"CRC32 `{c['crc32']}`") if c.get("sha1"): @@ -751,7 +751,7 @@ def _emulator_card_folds( open_lines = [d for d in key if not skipped(d)] if fnote: open_lines.append(data_root_words( - _escape_tags(link_prose_citations(profile, str(fnote))), data_href)) + escape_tags(link_prose_citations(profile, str(fnote))), data_href)) if not in_repo and f.get("unsourceable"): open_lines.append(_unsourceable_line(f)) lines = [f"- {d}" for d in open_lines] @@ -768,12 +768,12 @@ def _emulator_card_folds( tuple(f"- {h}" for h in _ENTRY_HASHES))]) words = words if len(words) <= 3 else [*words[:3], "more"] if members: - words.append(_count(len(members), "member")) + words.append(count_text(len(members), "member")) hidden_part = [*shut_fold, "", *members] if members else shut_fold body = (hidden_part if not read_fold else [ "", markup.block_open("div", f'class="rb-search-skip" {markup.search_exclude()}'), "", *hidden_part, "", "", "", *read_fold]) - fold = card_fold(_listed_words(words), body, skip=False) + fold = card_fold(listed_words(words), body, skip=False) # A fold the search skips whole sits in the skipped block before it, with # no attribute of its own: on a page of 200 MAME cards the attribute, the # class and a block each were 12 KB. @@ -793,25 +793,25 @@ def _held_copy_line(copy: tuple[str, str], consumers: FileConsumers) -> str: path, member = copy parts = path.rstrip("/").split("/") if member: - archive = _code(path) + archive = code_span(path) zsha1 = consumers.sha1_at(path) if zsha1 and len(parts) >= 3 and parts[0] == "bios": page = urllib.parse.quote(card_page(path, zsha1)) archive = f"[{archive}](../systems/{page}.md#sha1-{zsha1[:12]})" - return f"Collection copy: member {_code(member)} of {archive}" + return f"Collection copy: member {code_span(member)} of {archive}" if parts[0] == "data" and len(parts) >= 2: ref, inside = parts[1], "/".join(parts[2:]) if path.endswith("/"): - where = _code(inside + "/") if inside else "the tree" - return f"Collection copy: {where} in the {_code(ref)} data directory" - info = (_DATA_MEMBERS.get(ref) or {}).get(inside) or {} - shown = _code(inside) + where = code_span(inside + "/") if inside else "the tree" + return f"Collection copy: {where} in the {code_span(ref)} data directory" + info = (DATA_MEMBERS.get(ref) or {}).get(inside) or {} + shown = code_span(inside) if info.get("sha1"): shown = (f'' f"{html.escape(inside)}") - return f"Collection copy: {shown} in the {_code(ref)} data directory" + return f"Collection copy: {shown} in the {code_span(ref)} data directory" tree = f"{REPO_URL}/tree/main/{urllib.parse.quote(path.rstrip('/'))}" - return f"Collection copy: [{_code(path)}]({tree})" + return f"Collection copy: [{code_span(path)}]({tree})" def _directory_copies(entry: dict, consumers: FileConsumers) -> list[str]: @@ -826,11 +826,11 @@ def _directory_copies(entry: dict, consumers: FileConsumers) -> list[str]: return [] folder = os.path.commonpath(held) if len(held) > 1 else os.path.dirname(held[0]) parts = folder.split("/") - where = _code(folder + "/") + where = code_span(folder + "/") if len(parts) >= 3 and parts[0] == "bios": - where = f"[{where}]({console_href(_slug(parts[1]), parts[2], '../')})" + where = f"[{where}]({console_href(manufacturer_slug(parts[1]), parts[2], '../')})" tree = f"{REPO_URL}/tree/main/{urllib.parse.quote(folder)}" - return [f"Collection copies: {_count(len(members), 'file')} under {where} " + return [f"Collection copies: {count_text(len(members), 'file')} under {where} " f"([browse]({tree}))"] @@ -874,7 +874,7 @@ def _version_said(value: object, basis: dict, profile: dict, mode: str = "") -> url = version_basis_url(profile, basis, mode) if kind in ("file", "tag") else "" def shown(text: object) -> str: - return f"[{_code(str(text))}]({url})" if url else _code(str(text)) + return f"[{code_span(str(text))}]({url})" if url else code_span(str(text)) if kind == "file": return f"{value}, stated in {shown(basis.get('path'))}" @@ -999,7 +999,7 @@ def with_archive_counts(page: str, counts: dict[str, int]) -> str: return _ARCHIVE_BLOCK.sub(lambda m: f"{m.group(1)}{block}{m.group(3)}", page, count=1) -def _render_metadata_rows(profile: dict) -> list[str]: +def render_metadata_rows(profile: dict) -> list[str]: """Scalar profile fields, one table row each. Anything structured belongs in a collapsible block below, not in a @@ -1034,9 +1034,9 @@ def _render_metadata_rows(profile: dict) -> list[str]: and not str(val).startswith(("/", "~", "$")) and ":" not in str(val): # A bare `bios/` read as a place on the device: it is a folder # inside the app's own data folder, which the notes describe. - lines.append(f"| {label} | {_code(val)}, inside the app's own data folder |") + lines.append(f"| {label} | {code_span(val)}, inside the app's own data folder |") elif field == "bios_size" and isinstance(val, int): - lines.append(f"| {label} | {_fmt_size(val)} ({val:,} bytes) |") + lines.append(f"| {label} | {fmt_size(val)} ({val:,} bytes) |") elif isinstance(val, str) and val.startswith("http"): lines.append(f"| {label} | [{val}]({val}) |") else: @@ -1047,17 +1047,17 @@ def _render_metadata_rows(profile: dict) -> list[str]: for key in ("windows", "macos", "linux", "android", "ios"): root = roots.get(key) if isinstance(root, dict) and root.get("path"): - lines.append(f"| Data folder ({_OS_LABELS[key]}) | " - f"{_under_root(str(root['path']), '')} |") + lines.append(f"| Data folder ({OS_LABELS[key]}) | " + f"{under_root(str(root['path']), '')} |") if profile.get("source_ref"): lines.append( - f"| Source ref | {_source_ref_markdown(profile, profile['source_ref'])} |" + f"| Source ref | {source_ref_markdown(profile, profile['source_ref'])} |" ) return lines # Data directory members and revisions, read once per build. -_DATA_MEMBERS: dict[str, dict[str, dict]] = {} +DATA_MEMBERS: dict[str, dict[str, dict]] = {} def any_name_bios(profile: dict) -> dict | None: @@ -1080,7 +1080,7 @@ def any_name_bios(profile: dict) -> dict | None: return required[0] -def _named_example(name: str) -> bool: +def named_example(name: str) -> bool: """A real file name, not a placeholder such as `.bin`.""" return bool(name) and "<" not in name @@ -1091,5 +1091,5 @@ def _unsourceable_line(f: dict) -> str: same-named file from being served in its place: the file is still wanted, and "Not collectable" sent readers away from KANJI2.ROM, which MAME's fm7740sx.zip carries.""" - return (f"Not collected yet: {_escape_tags(str(f['unsourceable']))} " + return (f"Not collected yet: {escape_tags(str(f['unsourceable']))} " "([files not collected yet](../gaps.md#not-collected-yet))") diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py index 99f81a721..fddbaa304 100644 --- a/scripts/sitegen/emulatorpage.py +++ b/scripts/sitegen/emulatorpage.py @@ -12,30 +12,30 @@ from model.systemnames import system_name from packs.crossref import FileConsumers from sitegen import entries as siteentries, markup, measurements as sitemeasurements from sitegen.cards import ROMSET_FAQ, emulator_file_anchors -from sitegen.config import REPO_URL, _date_line, yaml +from sitegen.config import REPO_URL, date_line, yaml from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT -from sitegen.descriptions import _said_as_list +from sitegen.descriptions import said_as_list from sitegen.emulatorcards import ( CardLayout, - _DATA_MEMBERS, - _build_rows, - _entry_label, - _file_badges, - _named_example, - _named_system_link, - _region_words, - _render_emulator_file, - _render_metadata_rows, + DATA_MEMBERS, + build_rows, + entry_label, + file_badges, + named_example, + named_system_link, + region_words, + render_emulator_file, + render_metadata_rows, any_name_bios, emulator_romset, version_markdown, ) from sitegen.emulatorsindex import CLS_LABEL_ONE -from sitegen.fields import _render_platform_details, _render_structured_blocks, search_excluded -from sitegen.home import _next_block +from sitegen.fields import render_platform_details, render_structured_blocks, search_excluded +from sitegen.home import next_block from sitegen.install import ( - _install_block, - _platform_display, + install_block, + platform_display, comes_with_app, data_folder_block, data_root_words, @@ -43,16 +43,16 @@ from sitegen.install import ( ) from sitegen.lookup import data_directory_origin, data_tree_pages from sitegen.render import ( - _admonition_body, - _code, - _count, - _escape_tags, - _fmt_size, + admonition_body, + code_span, + count_text, + escape_tags, + fmt_size, card_page, record_emulator_cards, ) -from sitegen.sources import _source_ref_markdown, link_prose_citations, revision_markdown -from sitegen.startwith import _parts +from sitegen.sources import source_ref_markdown, link_prose_citations, revision_markdown +from sitegen.startwith import card_runs from sitegen.structured import emulator_file_aliases @@ -69,7 +69,7 @@ def _distinct_spellings(names: list) -> list[str]: return list(seen.values()) -def _availability_check( +def availability_check( db: dict, data_names: set[str] | None, owner: str = "", ) -> Callable[[dict], bool]: """A predicate answering whether the collection holds a file. @@ -156,7 +156,7 @@ def _regional_set(requirements: list[list[dict]]) -> list[dict]: members = requirements[0] if not all(f.get("region") for f in members): return [] - return members if len({_region_words(f["region"]) for f in members}) >= 2 else [] + return members if len({region_words(f["region"]) for f in members}) >= 2 else [] def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> list[str]: @@ -180,7 +180,7 @@ def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> lis # Sentences, one number format: the line read "1,563 files | 164 # required, 1399 optional | 1563 in repo". - total = f"**{_count(len(slots), 'file')}**" + total = f"**{count_text(len(slots), 'file')}**" if sum(len(group) for group in slots) != len(slots): total += f" ({sum(len(group) for group in slots):,} accepted versions)" line = f"{total}: {req_count:,} required, {optional:,} optional." @@ -198,7 +198,7 @@ def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> lis if hle_count: line += f" {hle_count:,} {'has' if hle_count == 1 else 'have'} an HLE fallback." if shipped: - line += f" {_count(shipped, 'more file')} {'comes' if shipped == 1 else 'come'} with the app." + line += f" {count_text(shipped, 'more file')} {'comes' if shipped == 1 else 'come'} with the app." lines = [line, ""] categories = [f.get("category", "bios") for f in files] @@ -210,7 +210,7 @@ def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> lis ) if categories.count(key) ] - lines.extend([f"By kind: {_said_as_list(cats)}.", ""]) + lines.extend([f"By kind: {said_as_list(cats)}.", ""]) return lines @@ -228,16 +228,16 @@ def _emulator_held_line(files: list[dict], available: Callable[[dict], bool]) -> held = [f"{in_repo:,} in repo", f"{len(slots) - in_repo - unsourceable:,} missing"] if unsourceable: held.append(f"{unsourceable:,} unsourceable") - return [f"

In this collection: {_said_as_list(held)}.

", ""] + return [f"

In this collection: {said_as_list(held)}.

", ""] -_DATA_REVISIONS: dict[str, dict] = {} +DATA_REVISIONS: dict[str, dict] = {} # Emulator -> the platforms that run it, as resolve_platform_cores answers. -_EMULATOR_SETUPS: dict[str, list[str]] = {} +EMULATOR_SETUPS: dict[str, list[str]] = {} # The measurement index items of each emulator, for the proof lines of its page. -_MEASUREMENT_ITEMS: dict[str, list[dict]] = {} +MEASUREMENT_ITEMS: dict[str, list[dict]] = {} # The emulator pages that list each data directory, by ref. -_DATA_READERS: dict[str, list[tuple[str, str]]] = {} +DATA_READERS: dict[str, list[tuple[str, str]]] = {} def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[str]) -> list[str]: @@ -252,7 +252,7 @@ def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[ anchor = f"sha1-{sha1[:12]}" span = "" if anchor in anchors else f'' anchors.add(anchor) - table.append(f"| {span}{_code(member)} | {_fmt_size(int(info.get('size', 0)))} | {_code(sha1)} |") + table.append(f"| {span}{code_span(member)} | {fmt_size(int(info.get('size', 0)))} | {code_span(sha1)} |") return table @@ -260,16 +260,16 @@ def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]], index: int) -> str: """One page of a large data directory's file list.""" stem, names = pages[index] - members = _DATA_MEMBERS.get(ref) or {} + members = DATA_MEMBERS.get(ref) or {} part = f" (part {index + 1} of {len(pages)})" if len(pages) > 1 else "" - read_by = _said_as_list([f"[{_escape_tags(display)}]({key}.md#data-directories)" - for key, display in _DATA_READERS.get(ref, [])]) + read_by = said_as_list([f"[{escape_tags(display)}]({key}.md#data-directories)" + for key, display in DATA_READERS.get(ref, [])]) # A file list out of the search: "dolphin" found three parts of the # dolphin-sys tree, on their title, before the Dolphin page. front: dict = {"level": "reference", "search": "exclude"} # The reader the tree is named after (dolphin for dolphin-sys), else # the first by name. - readers = _DATA_READERS.get(ref) or [] + readers = DATA_READERS.get(ref) or [] owner = max(readers, default=None, key=lambda reader: len(reader[0]) if ref.startswith(f"{reader[0]}-") else 0) if owner: @@ -284,14 +284,14 @@ def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]], *head, f"# The {ref} data directory{part}", "", f"{entry.get('description') or 'A data directory'}: " - f"{_count(len(members), 'file')}, as the packs ship them." + f"{count_text(len(members), 'file')}, as the packs ship them." + (f" Read by {read_by}." if read_by else ""), "", ] if len(pages) > 1: lines.extend([", ".join(f"[part {i}]({other}.md)" if other != stem else f"part {i}" for i, (other, _names) in enumerate(pages, 1)), ""]) lines.extend(search_excluded(_data_member_table(members, names, set()))) - lines.extend(["", _date_line()]) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" @@ -353,7 +353,7 @@ def _entry_row_words(files: list[dict], profile: dict, for f, row in zip(files, cells): filled.setdefault(_card_section(f), set()).update( column for column, cell in enumerate(row) if cell) - return [_html_words(_entry_label(f, profile)) + sum( + return [_html_words(entry_label(f, profile)) + sum( _html_words(cell) or column in filled[_card_section(f)] for column, cell in enumerate(row)) for f, row in zip(files, cells)] @@ -375,15 +375,15 @@ def emulator_parts(name: str, files: list, profile: dict | None = None, words = _entry_row_words(files, profile, available or (lambda _f: True)) sizes = [words[i] for i in order] ceiling = max(EMULATOR_PART_WORDS, max(sizes)) - count = max(len(_parts(order, ceiling, sizes)), -(-len(files) // EMULATOR_CARDS_PER_PART)) + count = max(len(card_runs(order, ceiling, sizes)), -(-len(files) // EMULATOR_CARDS_PER_PART)) while True: # The fewest words a part can hold for the parts to be ``count``: # cut at the ceiling, the last part took what the others left. share = min(-(-sum(sizes) // count), ceiling) - runs = _parts(order, share, sizes) + runs = card_runs(order, share, sizes) while len(runs) > count: share = min(share + max(1, share // 50), ceiling) - runs = _parts(order, share, sizes) + runs = card_runs(order, share, sizes) if max(len(run) for run in runs) <= EMULATOR_CARDS_PER_PART: return [(f"{name}-files-{index}", run) for index, run in enumerate(runs, 1)] count += 1 @@ -396,7 +396,7 @@ def emulator_parts(name: str, files: list, profile: dict | None = None, # "7 files" block. A split emulator's card pages always use the table. EMULATOR_TABLE_MIN = 6 ENTRY_HEADS = ["File", "Contents", "Status", "Hash"] -# The end of the badge _file_badges writes for an entry of each section. +# The end of the badge file_badges writes for an entry of each section. _SECTION_BADGE = {"required": ">required", "optional": ">optional", "with_app": ">comes with the app"} @@ -418,7 +418,7 @@ def _entry_cells(f: dict, profile: dict, available: Callable[[dict], bool]) -> l many = len(profile.get("systems") or []) > 1 for_system = system_name(str(f["system"])) if f.get("system") and many else "" contents = f.get("contents") or [] - badges = _file_badges(f, available(f), for_system) + badges = file_badges(f, available(f), for_system) # The first badge says whether the entry is needed: under Required, # Optional or Comes with the app it repeats the section heading. # One element and two words fewer on each of MAME's 1,563 rows. @@ -481,7 +481,7 @@ def _summary_table(files: list[dict], indexes: list[int], cell: Callable[[int, s if needed == "yes" and multi_system and f.get("system"): needed = f"for {system_name(str(f['system']))}" rows.append((cell(i, str(f.get("path") or f.get("name", ""))), - _region_words(f.get("region"), 3), needed, _hash_short(f))) + region_words(f.get("region"), 3), needed, _hash_short(f))) keep = [0] + [column for column in (1, 3) if any(row[column] for row in rows)] if len({row[2] for row in rows}) > 1: keep.append(2) @@ -549,8 +549,8 @@ def _any_name_folder(profile: dict, entry: dict) -> str: # A bare `bios/` is a folder inside the app's own data folder. own = ("[the app's data folder](#data-folder)" if profile.get("data_root") else "the app's own data folder") - return f"the {_code(folder.strip('/'))} folder inside {own}" - return f"{_code(folder)}, inside the BIOS folder" + return f"the {code_span(folder.strip('/'))} folder inside {own}" + return f"{code_span(folder)}, inside the BIOS folder" def _any_name_steps(emu_name: str, profile: dict, entry: dict, href: str, @@ -564,10 +564,10 @@ def _any_name_steps(emu_name: str, profile: dict, entry: dict, href: str, """ system = system_name((profile.get("systems") or [""])[0]) example = str(entry.get("name") or "") - if _named_example(example) and href: - get = f"Download [{_code(example)}]({href})." + if named_example(example) and href: + get = f"Download [{code_span(example)}]({href})." else: - get = f"Get one from the {_named_system_link(profile['systems'][0], '../')} files." + get = f"Get one from the {named_system_link(profile['systems'][0], '../')} files." steps = [get] folders: list[str] = [] if profile.get("type") == "standalone" and standalone_place(name, profile, entry): @@ -630,7 +630,7 @@ def _emulator_intro(emu_name: str, profile: dict, href: str = "", name: str = "" sentences = [] if names: shown = names if len(names) <= 4 else names[:3] + [f"{len(names) - 3} more systems"] - sentences.append(f"{emu_name} emulates {_said_as_list(shown)}.") + sentences.append(f"{emu_name} emulates {said_as_list(shown)}.") regional = _regional_set(requirements) by_region = "" if regional else _regional_choice(required) others = len(files) - len(required) @@ -642,20 +642,20 @@ def _emulator_intro(emu_name: str, profile: dict, href: str = "", name: str = "" f"It needs one BIOS for the game's region, among the {len(regional):,} it accepts.") if others: sentences.append( - f"The {_count(others, 'other file')} {'is' if others == 1 else 'are'} optional.") + f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.") elif by_region: # Three required BIOS of three regions: the page said "3 of them # required" and read as "get all of these". sentences.append(f"It picks the BIOS for the game's region: {by_region}.") if others: sentences.append( - f"The {_count(others, 'other file')} {'is' if others == 1 else 'are'} optional.") + f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.") elif files: sentences.append( - f"It reads {_count(len(files), 'file')}, {len(requirements):,} of them required: " + f"It reads {count_text(len(files), 'file')}, {len(requirements):,} of them required: " "without a required file it does not start games." if requirements else - f"It reads {_count(len(files), 'file')}, none of them required: it starts " + f"It reads {count_text(len(files), 'file')}, none of them required: it starts " "games without them." ) if any(len(members) > 1 for members in requirements): @@ -679,9 +679,9 @@ def _regional_choice(required: list[dict], most: int = 6) -> str: """ if not required or len(required) > most or not all(f.get("region") for f in required): return "" - if len({_region_words(f["region"]) for f in required}) < 2: + if len({region_words(f["region"]) for f in required}) < 2: return "" - choices = [f"{f.get('name', '')} ({_region_words(f['region'], 3)})" for f in required] + choices = [f"{f.get('name', '')} ({region_words(f['region'], 3)})" for f in required] return ", ".join(choices[:-1]) + f" or {choices[-1]}" @@ -729,7 +729,7 @@ def _source_rows(profile: dict) -> list[str]: if gone: # The links above answer 451 or reach a domain someone else now # owns: said beside them, with the date the profile observed it. - rows.append(f"| Source status | gone: {_escape_tags(str(gone))} |") + rows.append(f"| Source status | gone: {escape_tags(str(gone))} |") mirror = profile.get("source_mirror") if mirror: rows.append(f"| Mirror | [{mirror}]({mirror}) |" if str(mirror).startswith("http") @@ -749,8 +749,8 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]: revision = revision_markdown(profile) if revision: rows.append(f"| Revision | {revision} |") - rows.extend(_build_rows(profile)) - setups = _EMULATOR_SETUPS.get(name) + rows.extend(build_rows(profile)) + setups = EMULATOR_SETUPS.get(name) if setups: # The file cards name the setups whose own list holds a file: the # ones that run the emulator and pack its files were said nowhere. @@ -758,7 +758,7 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]: # other pages over their element budget. Out of the search: setup # names on 530 pages ranked the data page first for "batocera folder". rows.append(f"| Run by | " + ", ".join( - f"[{_platform_display(p)}](../platforms/{p}.md)" for p in setups) + " |") + f"[{platform_display(p)}](../platforms/{p}.md)" for p in setups) + " |") rows.append(f"| Profiled | {profile.get('profiled_date', 'unknown')} |") # The YAML is the reusable document this site renders, and the JSON is the # same profile for a program. @@ -771,7 +771,7 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]: rows.append(f"| Cores | {', '.join(_distinct_spellings(cores))} |") systems = profile.get("systems", []) if systems: - sys_links = list(dict.fromkeys(_named_system_link(s, "../") for s in systems)) + sys_links = list(dict.fromkeys(named_system_link(s, "../") for s in systems)) rows.append(f"| Systems | {', '.join(sys_links)} |") author = profile.get("author", "") if author: @@ -779,7 +779,7 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]: based_on = profile.get("based_on", "") if based_on: rows.append(f"| Based on | {based_on} |") - rows.extend(_render_metadata_rows(profile)) + rows.extend(render_metadata_rows(profile)) return rows @@ -801,7 +801,7 @@ def _emulator_files_section( consumers = sources.consumers part_pages: dict[str, str] = {} lines: list[str] = [] - _file_available = _availability_check(sources.db, sources.data_names, name) + _file_available = availability_check(sources.db, sources.data_names, name) lines.extend(["## Files", ""]) lines.extend(_emulator_file_summary(files, profile.get("groups"))) @@ -813,7 +813,7 @@ def _emulator_files_section( data_href = f"{name}.md#data-folder" if parts else "#data-folder" table_form = markup.starlight() and (bool(parts) or len(files) >= EMULATOR_TABLE_MIN) cards = [ - _render_emulator_file(f, profile, consumers, files, _file_available, anchor, name, + render_emulator_file(f, profile, consumers, files, _file_available, anchor, name, CardLayout(alias, data_href, badges_apart=table_form)) for f, anchor, alias in zip(files, anchors, aliases) ] @@ -855,27 +855,27 @@ def _data_directory_lines( line += f": {entry['description']}" lines.append(line) lines.extend(f" - {line}" for line in data_directory_origin( - entry, _DATA_REVISIONS.get(ref) or {})) + entry, DATA_REVISIONS.get(ref) or {})) if dd.get("mode"): lines.append(f" - Read by the {dd['mode']} build only") if dd.get("bundled"): lines.append(" - Installed with the emulator, so packs leave it out") if dd.get("source_ref"): - lines.append(f" - Source: {_source_ref_markdown(profile, dd['source_ref'])}") - members = _DATA_MEMBERS.get(ref) or {} + lines.append(f" - Source: {source_ref_markdown(profile, dd['source_ref'])}") + members = DATA_MEMBERS.get(ref) or {} tree_pages = data_tree_pages(ref, members) if tree_pages: where = (f"[a page of their own]({tree_pages[0][0]}.md)" if len(tree_pages) == 1 else "pages of their own: " + ", ".join( f"[part {i}]({stem}.md)" for i, (stem, _names) in enumerate(tree_pages, 1))) - lines.append(f" - {_count(len(members), 'file')}, listed on {where}") + lines.append(f" - {count_text(len(members), 'file')}, listed on {where}") for index, (stem, _names) in enumerate(tree_pages): part_pages[stem] = _data_tree_page(ref, entry, tree_pages, index) elif members: table = _data_member_table(members, sorted(members), member_anchors) lines.append("") lines.extend(markup.details( - "info", f"{_count(len(members), 'file')}, as the packs ship them", + "info", f"{count_text(len(members), 'file')}, as the packs ship them", table, indent=" ")) return lines, part_pages @@ -957,12 +957,12 @@ def emulator_pages( # card took two screens above the files. lines.extend(markup.details("note", "About this profile", card)) - lines.extend(_install_block(name, profile)) + lines.extend(install_block(name, profile)) - lines.extend(_render_platform_details(profile)) + lines.extend(render_platform_details(profile)) if notes: - body = _admonition_body(data_root_words(link_prose_citations(profile, notes)) + body = admonition_body(data_root_words(link_prose_citations(profile, notes)) ).replace("\n ", "\n") lines.extend(markup.details("note", "Technical notes", body.split("\n"))) @@ -970,16 +970,16 @@ def emulator_pages( lines.append("No BIOS or firmware files required.") if exclusion: lines.append("") - lines.extend(markup.aside("info", "Why no files", [_escape_tags(str(exclusion))])[:-1]) + lines.extend(markup.aside("info", "Why no files", [escape_tags(str(exclusion))])[:-1]) else: section, pages = _emulator_files_section( name, emu_name, profile, _EmulatorSources(db, consumers, data_names)) lines.extend(section) part_pages.update(pages) - lines.extend(sitemeasurements.proof_section(_MEASUREMENT_ITEMS.get(name, []))) + lines.extend(sitemeasurements.proof_section(MEASUREMENT_ITEMS.get(name, []))) - blocks = _render_structured_blocks(profile) + blocks = render_structured_blocks(profile) if blocks: lines.extend(["## Profile data", "", *blocks]) @@ -988,12 +988,12 @@ def emulator_pages( lines.extend(section) part_pages.update(pages) - lines.extend(_next_block([ + lines.extend(next_block([ "[Get the files](../which-pack.md), for the setup in use", "[Every system](../systems/index.md), and the files each one needs", "[When a game does not start](../wiki/troubleshooting.md)", ])) - lines.extend(["", _date_line()]) + lines.extend(["", date_line()]) return {name: "\n".join(lines) + "\n", **part_pages} @@ -1024,7 +1024,7 @@ def _card_index( return [ f"{emu_name} reads more files than one page holds: each entry below " - f"links to its card, on {_count(len(parts), 'page')}: " + f"links to its card, on {count_text(len(parts), 'page')}: " + ", ".join(f"[{number}]({stem}.md)" for number, (stem, _e) in enumerate(parts, 1)) + ".", "", @@ -1075,11 +1075,11 @@ def _emulator_part_page( f"# {emu_name} files, part {number} of {len(parts)}", "", # The crumbs end on the emulator, read from parent:. - f"This part holds {_count(len(files), 'entry', 'entries')}, " - f"{_code(first)} to {_code(last)}. The other parts: {others}.", + f"This part holds {count_text(len(files), 'entry', 'entries')}, " + f"{code_span(first)} to {code_span(last)}. The other parts: {others}.", "", *_sectioned(files, list(range(len(files))), render), ] - lines.extend(_next_block([f"[{emu_name}]({name}.md), the profile and every entry"])) - lines.extend(["", _date_line()]) + lines.extend(next_block([f"[{emu_name}]({name}.md), the profile and every entry"])) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" diff --git a/scripts/sitegen/emulatorsindex.py b/scripts/sitegen/emulatorsindex.py index 9f299779a..d390514e8 100644 --- a/scripts/sitegen/emulatorsindex.py +++ b/scripts/sitegen/emulatorsindex.py @@ -3,10 +3,10 @@ from __future__ import annotations from model.profiles import unique_emulator_profiles -from sitegen.emulatorcards import _named_system_link +from sitegen.emulatorcards import named_system_link -def _content_check_ceiling(profiles: dict) -> str: +def content_check_ceiling(profiles: dict) -> str: """How far content checking can reach across every profiled entry.""" hashed = sized = neither = 0 for profile in unique_emulator_profiles(profiles).values(): @@ -153,7 +153,7 @@ def generate_emulators_index(profiles: dict) -> str: emu_name = p.get("emulator", name) cls = p.get("core_classification", "other") systems = list(dict.fromkeys( - _named_system_link(s, "../") for s in p.get("systems") or [])) + named_system_link(s, "../") for s in p.get("systems") or [])) files = p.get("files", []) sys_str = ", ".join(systems[:3]) if len(systems) > 3: diff --git a/scripts/sitegen/fields.py b/scripts/sitegen/fields.py index f058072ae..15920171c 100644 --- a/scripts/sitegen/fields.py +++ b/scripts/sitegen/fields.py @@ -6,8 +6,8 @@ import re from collections.abc import Callable from sitegen import markup -from sitegen.render import _escape_tags, _field_text, _render_yaml_value -from sitegen.sources import _source_ref_markdown, link_prose_citations +from sitegen.render import escape_tags, scalar_text, render_yaml_value +from sitegen.sources import source_ref_markdown, link_prose_citations def search_excluded(lines: list[str]) -> list[str]: @@ -26,7 +26,7 @@ def search_excluded(lines: list[str]) -> list[str]: *lines, "", "", ""] -def _render_platform_details(profile: dict) -> list[str]: +def render_platform_details(profile: dict) -> list[str]: """The per-platform block, one level of nesting deep.""" lines: list[str] = [] platform_details = profile.get("platform_details") @@ -48,9 +48,9 @@ def _render_platform_details(profile: dict) -> list[str]: def _detail_value(profile: dict, key: object, value: object) -> str: """A platform detail, its citations linked at the profile's pin.""" if key == "source_ref" and isinstance(value, (str, dict)): - return _source_ref_markdown(profile, value) + return source_ref_markdown(profile, value) if isinstance(value, str): - return _escape_tags(link_prose_citations(profile, value)) + return escape_tags(link_prose_citations(profile, value)) return _plain_value(value) @@ -63,7 +63,7 @@ def _plain_value(value: object) -> str: return "none" if isinstance(value, (list, tuple)): return ", ".join(_plain_value(item) for item in value) - return _escape_tags(str(value)) + return escape_tags(str(value)) def _structured_field_text(profile: dict) -> Callable[[object, object], str]: @@ -74,15 +74,15 @@ def _structured_field_text(profile: dict) -> Callable[[object, object], str]: """ def text(key: object, value: object) -> str: if key == "source_ref" and isinstance(value, str): - return _source_ref_markdown(profile, value) + return source_ref_markdown(profile, value) if isinstance(value, str): - return link_prose_citations(profile, _field_text(key, value)) - return _field_text(key, value) + return link_prose_citations(profile, scalar_text(key, value)) + return scalar_text(key, value) return text -def _render_structured_blocks(profile: dict) -> list[str]: +def render_structured_blocks(profile: dict) -> list[str]: """Every remaining structured field, as a collapsible section.""" lines: list[str] = [] _structured_blocks = [ @@ -115,12 +115,12 @@ def _render_structured_blocks(profile: dict) -> list[str]: if val is None: continue body: list[str] = [] - _render_yaml_value(body, val, indent=0, + render_yaml_value(body, val, indent=0, field_text=_structured_field_text(profile)) # Closed: raw profile data, below the files (Cemu's firmware # titles opened the page above them). block = markup.details( - "abstract", label, [_escape_tags(line) for line in body]) + "abstract", label, [escape_tags(line) for line in body]) # A block listing hashes is the lookup's, as a card's hash lines are: # izapple2's ROM table put "md5" 59 times in the search, above the # page that explains MD5 checks. @@ -131,7 +131,7 @@ def _render_structured_blocks(profile: dict) -> list[str]: return lines -def _hash_spans(value: str | list, copy: bool = False) -> str: +def hash_spans(value: str | list, copy: bool = False) -> str: """Each hash a profile accepts, in full, each with a copy button when *copy*. diff --git a/scripts/sitegen/gaps.py b/scripts/sitegen/gaps.py index 6a647828f..15add3f13 100644 --- a/scripts/sitegen/gaps.py +++ b/scripts/sitegen/gaps.py @@ -11,14 +11,14 @@ from model.platforms import native_layer from resolve.cores import resolve_platform_cores from resolve.nativemode import check_label from sitegen import markup, wanted as sitewanted -from sitegen.cards import _PROVENANCE_LABELS, _fetch_url -from sitegen.config import _date_line -from sitegen.crossref import _gap_sources +from sitegen.cards import PROVENANCE_LABELS, fetch_url +from sitegen.config import date_line +from sitegen.crossref import gap_sources from sitegen.dataexports import build_emulator_gap_report -from sitegen.emulatorsindex import _content_check_ceiling -from sitegen.parts import _list_pages -from sitegen.render import _code, _count, _escape_tags -from sitegen.sources import _source_ref_markdown +from sitegen.emulatorsindex import content_check_ceiling +from sitegen.parts import list_pages +from sitegen.render import code_span, count_text, escape_tags +from sitegen.sources import source_ref_markdown # Contributing page @@ -87,7 +87,7 @@ def short_hash(value: str) -> str: column on every screen.""" value = str(value) if len(value) <= 12: - return _code(value) + return code_span(value) return f'{html.escape(value[:12])}' @@ -102,8 +102,8 @@ def _catalogued_needs(report: dict | None) -> dict[tuple[str, str], list[str]]: imported romset lists that file, from a provenance report built with the profiles' needs.""" return { - need: [f"{_escape_tags(where)} `{_escape_tags(name)}`" for where, name in listed] - for need, listed in sitewanted.catalog_listings(report, _PROVENANCE_LABELS).items() + need: [f"{escape_tags(where)} `{escape_tags(name)}`" for where, name in listed] + for need, listed in sitewanted.catalog_listings(report, PROVENANCE_LABELS).items() } @@ -122,7 +122,7 @@ def _copy_cell(path: str, algos: list[str], db: dict | None) -> str: {}, ) hashes = {algo: [str(record[algo]).lower()] for algo in algos if record.get(algo)} - shown = f"[{_code(path)}]({_fetch_url(path)})" + shown = f"[{code_span(path)}]({fetch_url(path)})" return f"{shown}
{_hash_cell(hashes)}" if hashes else shown @@ -181,7 +181,7 @@ def _render_problem_files( total_problems = len(missing_files) + len(untested_files) + len(mismatch_files) # One row per name: the page opened on "48 are missing", counted by # destination, above a heading that said "10 files". Both are said. - names = _count(len(missing_files), "name") + names = count_text(len(missing_files), "name") missing_said = (f"{missing_total:,} missing under {names}" if missing_total is not None else f"{len(missing_files)} missing") @@ -197,7 +197,7 @@ def _render_problem_files( if missing_files: lines.extend([ f'### Missing ' - f"{_count(len(missing_files), 'name')}", + f"{count_text(len(missing_files), 'name')}", "", "Required is the platform's own flag. Category says what the " "platform's emulators do with the file: `bios` is firmware they " @@ -217,7 +217,7 @@ def _render_problem_files( plats = "; ".join( (f"[{display}](platforms/{key}.md#{system.replace(' ', '-')})" if key and system else display) - + " " + ", ".join(_code(dest) for dest in sorted(dests)) + + " " + ", ".join(code_span(dest) for dest in sorted(dests)) for (display, key, system), dests in sorted(f["where"].items()) ) cats = f["categories"] @@ -228,7 +228,7 @@ def _render_problem_files( if untested_files: lines.extend([ f'### Untested ' - f"{_count(len(untested_files), 'file')}", + f"{count_text(len(untested_files), 'file')}", "", "Present, but not the expected hash. Declared is what the platform " "asks for, the collection copy is what the path holds.", @@ -241,7 +241,7 @@ def _render_problem_files( plats = ", ".join(sorted(set(f["platforms"]))) declared = f["declared"] lines.append( - f"| {_code(f['name'])} | {plats} | {_reason_cell(f['reason'])} " + f"| {code_span(f['name'])} | {plats} | {_reason_cell(f['reason'])} " f"| {_hash_cell(declared) or '-'} " f"| {_copy_cell(f['path'], list(declared) or ['md5'], db)} |" ) @@ -250,7 +250,7 @@ def _render_problem_files( if mismatch_files: lines.extend([ f'### Discrepancy ' - f"{_count(len(mismatch_files), 'file')}", + f"{count_text(len(mismatch_files), 'file')}", "", "The platform's own check passes, but the emulator's size or " "hash check fails. Each row names the check that fails.", @@ -262,7 +262,7 @@ def _render_problem_files( f = mismatch_files[fname] plats = ", ".join(sorted(set(f["platforms"]))) held = _held_accepted(f["discrepancy"], db) - cell = f"[{_code(held)}]({_fetch_url(held)})" if held else "-" + cell = f"[{code_span(held)}]({fetch_url(held)})" if held else "-" lines.append(f"| `{fname}` | {plats} | {_reason_cell(f['discrepancy'])} | {cell} |") lines.append("") @@ -278,8 +278,8 @@ def _render_problem_files( "|------|----------|--------|--------------|", ]) lines.extend( - f"| {_code(p['name'])} | {_escape_tags(p['platform'])} | {p['status']} " - f"| {_code(p['held_by'])} |" + f"| {code_span(p['name'])} | {escape_tags(p['platform'])} | {p['status']} " + f"| {code_span(p['held_by'])} |" for p in sorted(settled, key=lambda row: (row["name"], row["platform"])) ) lines.append("") @@ -601,9 +601,9 @@ def _source_row(m: dict, profiles: dict, coverages: dict, req = "yes" if m["required"] else "no" algorithm, _, value = m["identity"].partition(":") expected = f"{algorithm} {short_hash(value)}" if value else "-" - destination = _code(m["path"]) if m["path"] != m["name"] else "-" + destination = code_span(m["path"]) if m["path"] != m["name"] else "-" emulators = ", ".join( - f"[{_escape_tags(display)}](emulators/{key}.md)" + f"[{escape_tags(display)}](emulators/{key}.md)" for display, key in zip(m["emulators"], m["emu_keys"]) ) owner = profiles[m["emu_keys"][0]] @@ -613,7 +613,7 @@ def _source_row(m: dict, profiles: dict, coverages: dict, return ( f"| `{m['name']}` [Have it? Upload]({upload}) | {destination} | {expected} " f"| {emulators} | {req} | {plat_badges} | " - f"{_source_ref_markdown(owner, m['source_ref'])} |" + f"{source_ref_markdown(owner, m['source_ref'])} |" ) @@ -621,9 +621,9 @@ def _source_counted(missing: _MissingFiles) -> str: """How many files there are to source, and the entries they come from.""" req_src = [m for m in missing.rows if m["required"]] return ( - f"{_count(len(missing.rows), 'file')}, {len(req_src)} required." + f"{count_text(len(missing.rows), 'file')}, {len(req_src)} required." + ( - f" They come from {_count(missing.entries, 'entry', 'entries')}: a file " + f" They come from {count_text(missing.entries, 'entry', 'entries')}: a file " "declared with the same hash at several places is listed once." if missing.entries != len(missing.rows) else "" ) @@ -638,7 +638,7 @@ def _source_table(counted: str, rows: list[str], moved: dict[str, str] | None) - ] if moved is None: return [*head, *rows, ""] - where = _list_pages( + where = list_pages( "gaps-files-to-source", "Files to source", f"{counted} Each is a file an emulator loads that no platform lists and " "the collection does not hold. Part of " @@ -657,7 +657,7 @@ def _bundled_note(bundled_rows: set[tuple[str, str]]) -> list[str]: emulators = sorted({emulator for emulator, _name in bundled_rows}) return [ f"{len(bundled_rows)} further files arrive with their emulator's own " - f"package ({_escape_tags(', '.join(emulators))}): documented in the profile, not " + f"package ({escape_tags(', '.join(emulators))}): documented in the profile, not " "collected, and not listed here.", "", ] @@ -675,7 +675,7 @@ def _undeclared_gaps(report_all: dict) -> tuple[dict[str, int], int, list[tuple[ if data["gaps"] == 0: continue total_undeclared += data["gaps"] - for key, count in _gap_sources(data).items(): + for key, count in gap_sources(data).items(): src_totals[key] += count emulator_gaps.append((emu_name, data)) return src_totals, total_undeclared, emulator_gaps @@ -686,7 +686,7 @@ def _complement_rows(emulator_gaps: list[tuple[str, dict]]) -> list[str]: rows = [] for emu_name, data in sorted(emulator_gaps, key=lambda x: -x[1]["gaps"]): display = data["emulator"] - sources = _gap_sources(data) + sources = gap_sources(data) to_source = sources["missing"] missing_str = ( f'{to_source}' @@ -721,7 +721,7 @@ def _complement_intro(src_totals: dict[str, int], total_undeclared: int, "## Files emulators load that no platform lists { #core-complement }", "", f"Files loaded by emulators but not declared by any platform. " - f"{total_undeclared:,} files across {_count(len(emulator_gaps), 'emulator')}, " + f"{total_undeclared:,} files across {count_text(len(emulator_gaps), 'emulator')}, " f"{total_available:,} available ({pct_available}), " f"{src_totals['bundled']:,} installed with their emulator, " f"{src_totals['missing']:,} to source.", @@ -786,7 +786,7 @@ def _not_collected_section(report_all: dict, profiles: dict, catalogued: dict | where = listed.get((u["emu_key"], str(u["name"]).casefold()), []) lines.append( f"| `{u['name']}` | {u['emulator']} | {_reason_cell(u['reason'])} " - f"| {_source_ref_markdown(profiles[u['emu_key']], u['source_ref'])} " + f"| {source_ref_markdown(profiles[u['emu_key']], u['source_ref'])} " f"| {', '.join(where) or '-'} |" ) lines.append("") @@ -931,7 +931,7 @@ def generate_gap_analysis( "", _CORROBORATION_NOTE, "", - _content_check_ceiling(profiles), + content_check_ceiling(profiles), "", ]) @@ -964,5 +964,5 @@ def generate_gap_analysis( lines.extend(_not_collected_section(report_all, profiles, catalogued)) - lines.extend(["", _date_line()]) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" diff --git a/scripts/sitegen/getpages.py b/scripts/sitegen/getpages.py index fd01041a9..b5132225f 100644 --- a/scripts/sitegen/getpages.py +++ b/scripts/sitegen/getpages.py @@ -12,21 +12,22 @@ from model.platforms import load_platform_config from model.registry import load_platform_registry from installer_build.handhelds import GROUP_PAGE from sitegen import handheld as sitehandheld, markup -from sitegen.config import RELEASE_URL, REPO_URL, _REPO_ROOT +from sitegen.config import RELEASE_URL, REPO_URL +from core.paths import REPO_ROOT from sitegen.descriptions import PAGE_DATA from sitegen.guidepage import ( NO_ZIP_FAQ, - _folder_words, - _setup_relative, - _setup_routes, + folder_words, + setup_relative, + setup_routes, get_page_title, no_zip_line, ) -from sitegen.home import _next_block +from sitegen.home import next_block from sitegen.install import has_release_pack -from sitegen.parts import _parent_front_matter +from sitegen.parts import parent_front_matter from sitegen.readme import asset_links -from sitegen.render import _fmt_size +from sitegen.render import fmt_size from sitegen.versions import release_line, version_line @@ -35,11 +36,11 @@ def _unzip_into(platform_name: str, display: str, extract_to: str | None, parts: writes relative to the setup's own (`system/`, `bios/`) is named as the setup's, with the way to find it.""" what = "them all" if parts > 1 else "it" - if not _setup_relative(extract_to): - return [f"- Unzip {what} into {_folder_words(display, extract_to)}.", ""] + if not setup_relative(extract_to): + return [f"- Unzip {what} into {folder_words(display, extract_to)}.", ""] lead = GUIDES[platform_name].lead if platform_name in GUIDES else "" return [ - f"- Unzip {what} into {_folder_words(display, extract_to)}. " + f"- Unzip {what} into {folder_words(display, extract_to)}. " f"[Where is it?](../platforms/{platform_name}.md#where-the-files-go)", "", *([lead, ""] if lead else []), @@ -66,13 +67,13 @@ def generate_get_page(platform_name: str) -> str: if released and pack and tag_date: PAGE_DATA[f"{releaserecord.GET_DIR}/{platform_name}.md"] = {"dateModified": "-".join(tag_date.groups())} if released and pack and pack.get("assets"): - description = (f"The BIOS pack for {display}: {_fmt_size(pack['download_size'])} to " + description = (f"The BIOS pack for {display}: {fmt_size(pack['download_size'])} to " "download. The address stays the same and always gives the latest ZIP.") else: description = f"The BIOS files for {display}: one command installs and checks them." lines = [ "---", "search: exclude", f"description: {json.dumps(description)}", - *_parent_front_matter((display, f"/platforms/{platform_name}/")), "---", "", + *parent_front_matter((display, f"/platforms/{platform_name}/")), "---", "", f"# {title}", "", ] if released and pack and pack.get("assets"): @@ -85,8 +86,8 @@ def generate_get_page(platform_name: str) -> str: asset_links(platform_name, record, REPO_URL, f"Download {display} Pack", button=lambda text, url: markup.button(text, url, primary=True)), "", - f"- {_fmt_size(pack['download_size'])} to download, " - f"{_fmt_size(pack['extracted_size'])} once unzipped.", + f"- {fmt_size(pack['download_size'])} to download, " + f"{fmt_size(pack['extracted_size'])} once unzipped.", *(["- Both parts are needed." if parts == 2 else f"- All {parts} parts are needed."] if parts > 1 else []), *_unzip_into(platform_name, display, extract_to, parts), @@ -99,7 +100,7 @@ def generate_get_page(platform_name: str) -> str: f"No {display} ZIP yet. The next release has one. " "The command installs every file and checks it.", "", - *_setup_routes(platform_name, display), + *setup_routes(platform_name, display), ] elif released: lines += [ @@ -112,12 +113,12 @@ def generate_get_page(platform_name: str) -> str: lines += [ no_zip_line(display), "", - *_setup_routes(platform_name, display), + *setup_routes(platform_name, display), f"[Why no ZIP?](../{NO_ZIP_FAQ})", "", ] - lines += sitehandheld.platform_block(platform_name, _REPO_ROOT) - lines += _next_block([ + lines += sitehandheld.platform_block(platform_name, REPO_ROOT) + lines += next_block([ f"[{display}](../platforms/{platform_name}.md#install): the folder, " "and how to run the command on the device", "[All installer options](../wiki/installer.md)", diff --git a/scripts/sitegen/guidepage.py b/scripts/sitegen/guidepage.py index 130ef1fad..7e1ee5626 100644 --- a/scripts/sitegen/guidepage.py +++ b/scripts/sitegen/guidepage.py @@ -7,7 +7,7 @@ import json from model import releaserecord from model import siteinputs -from model.collection import _profiles_on_disk +from model.collection import profiles_on_disk from model.guides import ( GUIDES, Guide, @@ -21,12 +21,12 @@ from model.registry import load_platform_registry from resolve.nativemode import digest_algorithm from installer_build.handhelds import GROUP_PAGE from sitegen import handheld as sitehandheld, markup -from sitegen.config import _REPO_ROOT +from core.paths import REPO_ROOT from sitegen.guides import platform_args, terminal_tabs -from sitegen.home import _next_block -from sitegen.install import _installer, has_release_pack +from sitegen.home import next_block +from sitegen.install import installer_module, has_release_pack from sitegen.readme import download_links, extract_notes -from sitegen.render import _fmt_size +from sitegen.render import fmt_size from sitegen.versions import release_line, setup_version, version_line @@ -52,12 +52,12 @@ def get_page_title(platform_name: str, display: str) -> str: A profile listing no file (the RetroArch frontend) titles its page "... emulator", which no setup title repeats.""" kind = "BIOS pack" if has_release_pack(platform_name) else "BIOS files" - if (_profiles_on_disk().get(platform_name) or {}).get("files"): + if (profiles_on_disk().get(platform_name) or {}).get("files"): return f"{kind} for {display}" return f"{display} {kind}" -def _setup_relative(extract_to: str | None) -> bool: +def setup_relative(extract_to: str | None) -> bool: """Whether the registry writes the folder relative to the setup's own (`system/`, `Firmware/`), not as a path the device reads.""" if not extract_to: @@ -65,17 +65,17 @@ def _setup_relative(extract_to: str | None) -> bool: return not extract_to.startswith(("/", "~", "<")) -def _folder_words(display: str, extract_to: str | None) -> str: +def folder_words(display: str, extract_to: str | None) -> str: """The folder a pack or a copy goes into, in words: the device's path, or a folder of the setup named as the setup's.""" if not extract_to: return "the BIOS folder" - if _setup_relative(extract_to): + if setup_relative(extract_to): return f"{display}'s `{extract_to.rstrip('/')}` folder" return f"`{extract_to}`" -def _pack_buttons(platform_name: str, label: str = "Pack", prefix: str = "../", +def pack_buttons(platform_name: str, label: str = "Pack", prefix: str = "../", display: str | None = None) -> str: """The way to the platform's ZIP from its setup page: a button to its get/ page, the release it comes from, and the setup version its list @@ -135,7 +135,7 @@ def first_screen_words() -> list[str]: read from install.py: the one-liner opens the full screen, and the page showed a line menu (Enter, i, c, q) nobody saw, whose keys had changed since.""" - installer = _installer() + installer = installer_module() # The screen it opens first: the setup found, or the list when none # is. Install comes on the next one, Choose systems beside it and named # above on the page. @@ -156,7 +156,7 @@ def check_pass_line() -> str: no file is missing or wrong (install.py EVERYTHING_IN_PLACE), read from the installer. Typed here, it kept "All files up to date." after the installer said "Everything is in place.".""" - return f"Good result: `{_installer().EVERYTHING_IN_PLACE}`" + return f"Good result: `{installer_module().EVERYTHING_IN_PLACE}`" # Under "From your computer": a device with no network installs from the ZIP # (`--from-pack`). The id is the one wiki/installer.md gives its section. @@ -233,7 +233,7 @@ def _card_route(name: str, display: str, guide: Guide) -> list[str]: for key in tabs} if guide.run != ("device",): lead = ("No network here? Run the command on a computer that has one, with a USB " - f"drive's folder after `--dest`. Then copy it into {_folder_words(display, extract_to)}.") + f"drive's folder after `--dest`. Then copy it into {folder_words(display, extract_to)}.") return [lead, "", *terminal_tabs(tabs, args, steps=False)] # A folder on the card's Linux partition: Windows and macOS show the # small boot partition alone, and no folder there fits --dest. @@ -253,7 +253,7 @@ def _get_page_line(name: str, display: str) -> list[str]: return [f"Link to share: [{get_page_title(name, display)}](../{get_page_link(name)})", ""] -def _setup_routes(name: str, display: str, page_link: bool = False) -> list[str]: +def setup_routes(name: str, display: str, page_link: bool = False) -> list[str]: """The ways to run the command for a setup no ZIP serves first, written once for its setup page and its get/ page: the network folder from a computer, the card from a computer when the device has no network, and @@ -299,7 +299,7 @@ def _computer_first(name: str, guide: Guide) -> bool: def _ships_neogeo(name: str) -> bool: """Whether the setup's files hold `neogeo.zip`, the archive a reader most often unzips by mistake: arcade BIOS sets are read zipped.""" - manifest = _REPO_ROOT / "install" / f"{name}.json" + manifest = REPO_ROOT / "install" / f"{name}.json" if not manifest.is_file(): return False files = json.loads(manifest.read_text(encoding="utf-8")).get("files", []) @@ -316,8 +316,8 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non if pack and pack.get("assets"): parts = len(pack["assets"]) bullets = [ - f"{_fmt_size(pack['download_size'])} to download, " - f"{_fmt_size(pack['extracted_size'])} once unzipped." + f"{fmt_size(pack['download_size'])} to download, " + f"{fmt_size(pack['extracted_size'])} once unzipped." ] if parts > 1: bullets.append("Both parts are needed." if parts == 2 else f"All {parts} parts are needed.") @@ -330,13 +330,13 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non if guide.download_hint and not _computer_first(name, guide): bullets.append(guide.download_hint) lines += [ - _pack_buttons(name, f"Download {display} Pack"), + pack_buttons(name, f"Download {display} Pack"), "", *(f"- {b}" for b in bullets), "", ] elif not has_release_pack(name): - lines += [_pack_buttons(name, display=display), ""] + lines += [pack_buttons(name, display=display), ""] elif record.get("tag"): made_from = setup_version(name) lines += [ @@ -345,7 +345,7 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non "", ] else: - lines += [_pack_buttons(name, f"Download {display} Pack"), ""] + lines += [pack_buttons(name, f"Download {display} Pack"), ""] return [*lines, *only_some_consoles(name, "../")] @@ -353,7 +353,7 @@ def only_some_consoles(name: str, prefix: str = "") -> list[str]: """The way to a smaller download, in the words Get the files uses.""" return [ f"Only some consoles? [Pick them]({prefix}which-pack.md?platform={name}" - f"#only-some-consoles), or the command's **{_installer().TUI_SYSTEMS_ROW}**.", + f"#only-some-consoles), or the command's **{installer_module().TUI_SYSTEMS_ROW}**.", "", ] @@ -468,14 +468,14 @@ def generate_handheld_guide(guide: HandheldGuide) -> str: *terminal_tabs(("windows", "macos", "linux"), args), SAFE_LINK, "", - *_next_block([ + *next_block([ f"[{display}]({guide.uses}.md): every folder and every file", "[When a game does not start](../wiki/troubleshooting.md)", ]), ]) + "\n" -def _platform_guide(name: str, display: str, cov: dict, registry: dict, no_list: bool) -> list[str]: +def platform_guide(name: str, display: str, cov: dict, registry: dict, no_list: bool) -> list[str]: """The guide part of a platform page: folder, command, pack, check, next. A system that runs only on its own device puts the computer route @@ -518,7 +518,7 @@ def _platform_guide(name: str, display: str, cov: dict, registry: dict, no_list: else: where = lines lines = [ - *_setup_routes(name, display, page_link=True), + *setup_routes(name, display, page_link=True), *_guide_download(name, display, guide, extract_to, "## Download"), *_offline_line(name), *where, @@ -537,7 +537,7 @@ def _platform_guide(name: str, display: str, cov: dict, registry: dict, no_list: MISSING_IN_PLACE, "", *([guide.finish, ""] if guide.finish else []), - *_next_block([ + *next_block([ "[First install, step by step](../wiki/first-install.md)", "[When a game does not start](../wiki/troubleshooting.md)", ]), diff --git a/scripts/sitegen/home.py b/scripts/sitegen/home.py index a0c98d44c..22f4ad1c1 100644 --- a/scripts/sitegen/home.py +++ b/scripts/sitegen/home.py @@ -11,13 +11,13 @@ from model.profiles import unique_emulator_profiles from model.registry import load_platform_registry from sitegen import markup from sitegen.readme import demo_description, demo_facts -from sitegen.render import _fmt_size +from sitegen.render import fmt_size # Home page -def _stat(value: str, label: str) -> list[str]: +def stat_block(value: str, label: str) -> list[str]: return [ markup.block_open("div", 'class="rb-stat"'), # One line, a space between: the page text read "168/168Coverage". @@ -27,7 +27,7 @@ def _stat(value: str, label: str) -> list[str]: ] -def _group_members(coverages: dict, registry: dict, group: str) -> list[str]: +def group_members(coverages: dict, registry: dict, group: str) -> list[str]: """Registered platforms of a device group, by display name.""" return sorted( (name for name in coverages if registry.get(name, {}).get("device_group") == group), @@ -35,7 +35,7 @@ def _group_members(coverages: dict, registry: dict, group: str) -> list[str]: ) -def _next_block(links: list[str]) -> list[str]: +def next_block(links: list[str]) -> list[str]: """Where to go from here, at the end of a page: a plain heading and a list. A tinted callout with a side stripe said the same as the pager.""" return ["## Next steps", "", *(f"- {link}" for link in links), ""] @@ -49,7 +49,7 @@ def _tiles(registry: dict, members: list[str], display: dict[str, str], prefix: return markup.platform_tiles([ *((display[name], f"{prefix}platforms/{name}.md", str(registry.get(name, {}).get("logo") or ""), - GUIDES[name].runs_on or _runs_on(registry.get(name, {}), GUIDES[name])) + GUIDES[name].runs_on or runs_on_text(registry.get(name, {}), GUIDES[name])) for name in members), *((tile.name, f"{prefix}{tile.link}", tile.logo, tile.text) for tile in GROUP_TILES.get(group, ())), @@ -64,7 +64,7 @@ def setup_picker(registry: dict, display: dict[str, str], prefix: str = "") -> l lines: list[str] = [] alone: list[str] = [] for group, (label, _description) in DEVICE_GROUPS.items(): - members = _group_keys(registry, group, display) + members = group_keys(registry, group, display) if len(members) == 1 and not GROUP_TILES.get(group): alone += members elif members: @@ -175,10 +175,10 @@ def generate_explore_index(db: dict, coverages: dict, profiles: dict) -> str: "", markup.block_open("div", 'class="rb-stats"'), "", - *_stat(f"{total_files:,}", COLLECTION_FILES_LABEL), - *_stat(str(setup_count()), "Setups supported"), - *_stat(str(emulator_count), "Emulators documented"), - *_stat(_fmt_size(total_size), "Size of the collection"), + *stat_block(f"{total_files:,}", COLLECTION_FILES_LABEL), + *stat_block(str(setup_count()), "Setups supported"), + *stat_block(str(emulator_count), "Emulators documented"), + *stat_block(fmt_size(total_size), "Size of the collection"), "", "", composition_sentence(db), @@ -226,7 +226,7 @@ def install_demo(variant: str = "default", name: str = "") -> list[str]: _OS_NAMES = {"windows": "Windows", "darwin": "macOS", "linux": "Linux"} -def _runs_on(entry: dict, guide: Guide) -> str: +def runs_on_text(entry: dict, guide: Guide) -> str: """Where a setup runs, read from the systems the installer detects it on.""" if guide.on_card: return "SD card, filled from a computer" @@ -243,7 +243,7 @@ def _runs_on(entry: dict, guide: Guide) -> str: return ", ".join(names) -def _group_keys(registry: dict, group: str, display: dict[str, str]) -> list[str]: +def group_keys(registry: dict, group: str, display: dict[str, str]) -> list[str]: return sorted( (k for k in registry if registry[k].get("device_group") == group), key=lambda k: display[k].casefold(), diff --git a/scripts/sitegen/install.py b/scripts/sitegen/install.py index cb9329c13..f6db95a33 100644 --- a/scripts/sitegen/install.py +++ b/scripts/sitegen/install.py @@ -16,19 +16,19 @@ from model.platforms import load_platform_config from model.registry import list_release_pack_platforms from resolve.layout import runs_standalone from sitegen import markup -from sitegen.config import _REPO_ROOT +from core.paths import REPO_ROOT from sitegen.fields import search_excluded from sitegen.guides import fence, platform_args, terminal_tabs -from sitegen.render import _code, _escape_tags -from sitegen.sources import _source_ref_markdown +from sitegen.render import code_span, escape_tags +from sitegen.sources import source_ref_markdown def has_release_pack(platform_name: str) -> bool: """Whether a release publishes a ZIP for the platform (`release_pack`).""" - return platform_name in _release_pack_platforms() + return platform_name in release_pack_platforms() -def _release_pack_platforms() -> frozenset[str]: +def release_pack_platforms() -> frozenset[str]: return _release_packs_in(str(siteinputs.current().platforms)) @@ -40,7 +40,7 @@ def _release_packs_in(platforms_dir: str) -> frozenset[str]: _platform_names: dict[str, str] = {} -def _platform_display(name: str) -> str: +def platform_display(name: str) -> str: """A setup's name as its platform file writes it: Batocera, not batocera.""" display = _platform_names.get(name) if display is None: @@ -87,14 +87,14 @@ def install_commands(args: str = "", indent: str = "", @functools.cache -def _installer() -> types.ModuleType: +def installer_module() -> types.ModuleType: """install.py, read as a module: the names `--emulator` accepts are its own (`emulator_names`).""" import importlib.util - spec = importlib.util.spec_from_file_location("install", _REPO_ROOT / "install.py") + spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py") if spec is None or spec.loader is None: - raise ImportError(f"cannot load {_REPO_ROOT / 'install.py'}") + raise ImportError(f"cannot load {REPO_ROOT / 'install.py'}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module @@ -104,9 +104,9 @@ def _installer() -> types.ModuleType: def _published_emulator_names() -> dict[str, dict[str, str]]: """Per published manifest, every name `--emulator` accepts there and the profile it stands for, as `install.py --list-emulators` prints them.""" - installer = _installer() + installer = installer_module() names: dict[str, dict[str, str]] = {} - for path in sorted((_REPO_ROOT / "install").glob("*.json")): + for path in sorted((REPO_ROOT / "install").glob("*.json")): manifest = json.loads(path.read_text(encoding="utf-8")) names[path.stem] = installer.emulator_names( manifest, manifest.get("files") or [], manifest.get("omitted_files") or []) @@ -186,7 +186,7 @@ def _said_or(names: list[str]) -> str: return names[0] if len(names) == 1 else ", ".join(names[:-1]) + f" or {names[-1]}" -def _install_block(name: str, profile: dict) -> list[str]: +def install_block(name: str, profile: dict) -> list[str]: """One command that installs this emulator's files where it reads them. The installer finds the setup and its BIOS folder, then keeps what this @@ -200,7 +200,7 @@ def _install_block(name: str, profile: dict) -> list[str]: if not command: return [] emu = str(profile.get("emulator") or name) - shown = [_platform_display(setup) for setup in setups] + shown = [platform_display(setup) for setup in setups] if profile.get("type") == "standalone": lead = (f"With {_said_or(shown)}: the installer finds {_said_or(shown)} and its " f"BIOS folder, then downloads only the files {emu} reads there and checks " @@ -302,11 +302,11 @@ def standalone_place(name: str, profile: dict, entry: dict, key: str = "") -> st return str(entry.get("standalone_path") or "") -_OS_LABELS = {"windows": "Windows", "macos": "macOS", "linux": "Linux", +OS_LABELS = {"windows": "Windows", "macos": "macOS", "linux": "Linux", "android": "Android", "ios": "iOS"} -def _under_root(root: str, folder: str) -> str: +def under_root(root: str, folder: str) -> str: """``root`` with ``folder`` below it, as code: each alternative of "$XDG_CONFIG_HOME/x, else ~/.config/x", and a root written in words ("the folder picked in the setup wizard") kept as words.""" @@ -315,11 +315,11 @@ def _under_root(root: str, folder: str) -> str: for alternative in root.split(", else "): alternative = alternative.strip() if " " in alternative and "/" not in alternative and not alternative.startswith("<"): - shown.append(f"{_code(folder + '/')} in {_escape_tags(alternative)}" - if folder else _escape_tags(alternative)) + shown.append(f"{code_span(folder + '/')} in {escape_tags(alternative)}" + if folder else escape_tags(alternative)) continue joined = alternative.rstrip("/") + (f"/{folder}" if folder else "") + "/" - shown.append(_code(joined)) + shown.append(code_span(joined)) return ", else ".join(shown) @@ -355,7 +355,7 @@ def data_folder_block(name: str, profile: dict, entries: list[dict] | None = Non if not isinstance(root, dict) or not root.get("path"): continue path = str(root["path"]) - line = _under_root(path, _data_root_folder(name, profile, key, entries)) + line = under_root(path, _data_root_folder(name, profile, key, entries)) if key == "android" and path.startswith("Android/data/"): line += ", on the internal storage." body = [line] @@ -365,9 +365,9 @@ def data_folder_block(name: str, profile: dict, entries: list[dict] | None = Non first = note.split(" ", 1)[0] if first.isalpha() and first.islower(): note = note[:1].upper() + note[1:] - body += ["", _escape_tags(note) + "."] - body += ["", f"Source: {_source_ref_markdown(profile, str(root['source_ref']))}"] - items.append((_OS_LABELS[key], body)) + body += ["", escape_tags(note) + "."] + body += ["", f"Source: {source_ref_markdown(profile, str(root['source_ref']))}"] + items.append((OS_LABELS[key], body)) if len(items) == 1: label, body = items[0] return [f"On {label}: {body[0]}", *body[1:], ""] @@ -380,7 +380,7 @@ def data_root_words(text: str, href: str = "#data-folder") -> str: return re.sub(r"\bdata_root\b", f"[the data folder]({href})", text) -def _platform_install_block(name: str, display: str, on_card: bool = False) -> list[str]: +def platform_install_block(name: str, display: str, on_card: bool = False) -> list[str]: """The platform's pack, installed file by file: what the ZIP holds, with resume, verification and only what is missing. @@ -462,7 +462,7 @@ def _install_picker(declared: list[tuple[str, str]]) -> list[str]: + (" selected" if (platform, system) == lead else "") + f' data-sh="{attribute(_install_args(platform, system, "sh"))}" ' f'data-ps="{attribute(_install_args(platform, system, "powershell"))}">' - + html.escape(_platform_display(platform) + (f" ({system})" if names[platform] > 1 else ""), + + html.escape(platform_display(platform) + (f" ({system})" if names[platform] > 1 else ""), quote=False) + "" for platform, system in declared) @@ -505,24 +505,24 @@ def _command_list(label: str, declared: list[tuple[str, str]], shell: str) -> li # inside a command. names = Counter(platform for platform, _system in declared) items = "".join( - f"
  • {html.escape(_platform_display(platform), quote=False)}" + f"
  • {html.escape(platform_display(platform), quote=False)}" + (f" ({html.escape(system, quote=False)})" if names[platform] > 1 else "") + f': {command(platform, system)}
  • ' for platform, system in declared) return [label, "", f"
      {items}
    ", ""] -def _console_install_block(console: str, declared: list[tuple[str, str]]) -> list[str]: +def console_install_block(console: str, declared: list[tuple[str, str]]) -> list[str]: """Each platform's command for one console, by the system id it gives it, for a terminal and for PowerShell, each under its setup's name: RetroBat had two lines and nothing said which was for the Neo Geo.""" if not declared: return [] sh = [line for platform, system in declared for line in ( - f"# {_platform_display(platform)}", + f"# {platform_display(platform)}", install_command("sh", f"--platform {platform} --system {shlex.quote(system)}"))] ps = [line for platform, system in declared for line in ( - f"# {_platform_display(platform)}", + f"# {platform_display(platform)}", install_command("powershell", f"--platform {platform} --system {_ps_quote(system)}"))] # The name last: "Install the Atari System 1 files" read as a count. A # label naming files already reads "Install these files": "Install diff --git a/scripts/sitegen/lookup.py b/scripts/sitegen/lookup.py index fda63e08c..6788829b7 100644 --- a/scripts/sitegen/lookup.py +++ b/scripts/sitegen/lookup.py @@ -11,19 +11,20 @@ from pathlib import Path from core.hashing import parse_hash_list from model import siteinputs -from model.collection import _slug +from model.collection import manufacturer_slug from model.systemnames import system_name from packs.crossref import FileConsumers -from sitegen.cards import _PROVENANCE_LABELS, _emulator_card_anchor, emulator_file_anchors -from sitegen.config import SITE_URL, _REPO_ROOT -from sitegen.render import _code, _slugify_anchor, card_page, emulator_card_page +from sitegen.cards import PROVENANCE_LABELS, emulator_card_anchor, emulator_file_anchors +from sitegen.config import SITE_URL +from core.paths import REPO_ROOT +from sitegen.render import code_span, slugify_anchor, card_page, emulator_card_page from sitegen.write import write_if_changed HASH_ALGORITHMS = ("sha1", "sha256", "md5", "crc32") -def _hash_values(value: object) -> list[str]: +def sorted_hash_values(value: object) -> list[str]: """Every accepted value of one hash field, lowercase. A field holds one value, a list of accepted revisions, or (Recalbox) a @@ -32,7 +33,7 @@ def _hash_values(value: object) -> list[str]: return sorted(parse_hash_list(value)) -def _site_path(markdown_target: str) -> str: +def site_path(markdown_target: str) -> str: """A page link as generators write it (systems/sony.md#psx) as a site-absolute path (/retrobios/systems/sony/#psx), which resolves the same from any document that holds it.""" @@ -107,7 +108,7 @@ def generate_files_page() -> str: ]) -def data_directory_members(install_dir: Path = _REPO_ROOT / "install") -> dict[str, dict[str, dict]]: +def data_directory_members(install_dir: Path = REPO_ROOT / "install") -> dict[str, dict[str, dict]]: """Each data directory's files with their sha1 and size, as the install manifests record them for the installer to check.""" members: dict[str, dict[str, dict]] = {} @@ -118,7 +119,7 @@ def data_directory_members(install_dir: Path = _REPO_ROOT / "install") -> dict[s return members -def data_directory_revisions(data_dir: Path = _REPO_ROOT / "data") -> dict[str, dict]: +def data_directory_revisions(data_dir: Path = REPO_ROOT / "data") -> dict[str, dict]: """The revision each data directory was fetched at, as refresh_data_dirs records it.""" path = data_dir / ".versions.json" if not path.is_file(): @@ -145,8 +146,8 @@ def data_directory_origin(entry: dict, fetched: dict) -> list[str]: sha = str(fetched.get("sha", "")).strip('"') if _GIT_COMMIT.fullmatch(sha): repo = _GITHUB_REPO.match(url) - commit = f"[{_code(sha[:12])}](https://github.com/{repo.group(1)}/commit/{sha})" \ - if repo else _code(sha) + commit = f"[{code_span(sha[:12])}](https://github.com/{repo.group(1)}/commit/{sha})" \ + if repo else code_span(sha) branch = str(fetched.get("version", "")) lines.append(f"Revision: {commit}" + ( f", the head of `{branch}` when fetched" if branch and branch != sha else "")) @@ -206,7 +207,7 @@ def file_location_items( if len(parts) < 3 or parts[0] != "bios": continue page = card_page(entry.get("path", ""), sha1) - items.append({"sha1": sha1, "url": _site_path(f"systems/{page}.md#sha1-{sha1[:12]}")}) + items.append({"sha1": sha1, "url": site_path(f"systems/{page}.md#sha1-{sha1[:12]}")}) # A data directory's files are listed on the page of an emulator reading # the tree: 2,534 hashes the packs ship were found nowhere on the site. owners = _data_member_owners(profiles or {}) @@ -223,7 +224,7 @@ def file_location_items( known.add(sha1) page = page_of.get(member, owners[ref]) items.append({"sha1": sha1, - "url": _site_path(f"emulators/{page}.md#sha1-{sha1[:12]}")}) + "url": site_path(f"emulators/{page}.md#sha1-{sha1[:12]}")}) return sorted(items, key=lambda item: item["sha1"]) @@ -244,19 +245,19 @@ def _console_system_names(profiles: dict, coverages: dict) -> dict[tuple[str, st own section that folder is: a collection file is named after the console it is filed under. A folder no id owns, or that two names own, is left out. """ - from model.systemnames import _own_section + from model.systemnames import own_section from sitegen.render import system_ids found: dict[tuple[str, str], set[str]] = {} for sys_id in system_ids(profiles, [c["config"] for c in coverages.values()]): - own = _own_section(sys_id) + own = own_section(sys_id) if own is not None: - found.setdefault((_slug(own[0]), own[1]), set()).add(system_name(sys_id)) + found.setdefault((manufacturer_slug(own[0]), own[1]), set()).add(system_name(sys_id)) return {key: next(iter(names)) for key, names in found.items() if len(names) == 1} -def _data_member_digests( - members: dict, data_registry: dict | None = None, root: Path = _REPO_ROOT, +def data_member_digests( + members: dict, data_registry: dict | None = None, root: Path = REPO_ROOT, ) -> dict[str, dict[str, str]]: """sha1 -> every hash the lookup takes, for each data directory member whose copy in the tree's local cache has the sha1 the manifest records. @@ -306,17 +307,17 @@ def retired_records(retired: dict[str, dict], files: dict, locations: list[dict] extra["successor"] = successor else: # The page its card was on: the reader lands among its neighbours. - url = _site_path(f"systems/{card_page(str(record.get('path', '')), sha1)}.md") + url = site_path(f"systems/{card_page(str(record.get('path', '')), sha1)}.md") for algorithm in HASH_ALGORITHMS: value = sha1 if algorithm == "sha1" else record.get(algorithm) records.extend({"value": one, "algorithm": algorithm, "layer": "retired", "name": str(record.get("name", "")), "sha1": sha1, - "url": url, **extra} for one in _hash_values(value)) + "url": url, **extra} for one in sorted_hash_values(value)) return records def _archive_member_records(entry: dict, sha1: str, url: str, - root: Path = _REPO_ROOT) -> list[dict]: + root: Path = REPO_ROOT) -> list[dict]: """The CRC32 of each member of a collection archive, read from its central directory. @@ -349,7 +350,7 @@ def _collection_lookup_records( str(info.get("sha1", "")): member.rsplit("/", 1)[-1] for tree in members.values() for member, info in sorted(tree.items()) } - member_digests = _data_member_digests(members) + member_digests = data_member_digests(members) records: list[dict] = [] for item in locations: sha1 = item["sha1"] @@ -364,13 +365,13 @@ def _collection_lookup_records( for algorithm in HASH_ALGORITHMS if algorithm in digests) continue parts = str(entry.get("path", "")).split("/") - held_by = named.get((_slug(parts[1]), parts[2])) if len(parts) > 3 else None + held_by = named.get((manufacturer_slug(parts[1]), parts[2])) if len(parts) > 3 else None for algorithm in HASH_ALGORITHMS: records.extend({ "value": value, "algorithm": algorithm, "layer": "collection", "name": str(entry.get("name", "")), "sha1": sha1, "url": item["url"], **({"system_name": held_by} if held_by else {}), - } for value in _hash_values(entry.get(algorithm))) + } for value in sorted_hash_values(entry.get(algorithm))) records += _archive_member_records(entry, sha1, item["url"]) return records @@ -381,7 +382,7 @@ def _platform_lookup_records(coverages: dict, consumers: FileConsumers | None) - records: list[dict] = [] for key, coverage in sorted(coverages.items()): for system_id, system in sorted((coverage["config"].get("systems") or {}).items()): - url = _site_path(f"platforms/{key}.md#{system_id.replace(' ', '-')}") + url = site_path(f"platforms/{key}.md#{system_id.replace(' ', '-')}") system_label = _lookup_system_name(system_id) for entry in system.get("files") or []: # A hash of a ROM inside the archive (zipped_file) designates @@ -394,7 +395,7 @@ def _platform_lookup_records(coverages: dict, consumers: FileConsumers | None) - "owner": key, "name": str(entry.get("name", "")), "url": url, **({"system_name": system_label} if system_label else {}), **({"sha1": archive} if archive else {}), - } for value in _hash_values(entry.get(algorithm))) + } for value in sorted_hash_values(entry.get(algorithm))) return records @@ -407,7 +408,7 @@ def _emulator_lookup_records(profiles: dict) -> list[dict]: entries = profile.get("files") or [] own_systems = [str(s) for s in profile.get("systems") or []] for entry, anchor in zip(entries, emulator_file_anchors(entries)): - url = _site_path(f"emulators/{emulator_card_page(key, anchor)}.md#{anchor}") + url = site_path(f"emulators/{emulator_card_page(key, anchor)}.md#{anchor}") sys_id = str(entry.get("system") or "") or ( own_systems[0] if len(own_systems) == 1 else "") entry_label = _lookup_system_name(sys_id) if sys_id else None @@ -421,7 +422,7 @@ def _emulator_lookup_records(profiles: dict) -> list[dict]: "value": value, "algorithm": algorithm, "layer": "emulator", "owner": key, "name": name, "url": url, **({"system_name": entry_label} if entry_label else {}), - } for value in _hash_values(holder.get(algorithm))) + } for value in sorted_hash_values(holder.get(algorithm))) return records @@ -468,8 +469,8 @@ def wanted_records(rows: list[dict]) -> list[dict]: knows has it, and never said the dump is wanted.""" records = [] for row in rows: - label = _PROVENANCE_LABELS.get(row["catalog"], row["catalog"]) - url = _site_path(f"provenance.md#{_slugify_anchor(label)}") + label = PROVENANCE_LABELS.get(row["catalog"], row["catalog"]) + url = site_path(f"provenance.md#{slugify_anchor(label)}") for algorithm in ("sha1", "md5", "crc32"): value = str(row.get(algorithm) or "").lower() if value: @@ -500,15 +501,15 @@ def _read_by_name(records: list[dict], files: dict, consumers: FileConsumers) -> entries = consumers.emulator_files.get(emulator) or [] if index is None or index >= len(entries): continue - anchor = _emulator_card_anchor(emulator, entries, index) - url = _site_path(f"emulators/{emulator_card_page(emulator, anchor)}.md#{anchor}") + anchor = emulator_card_anchor(emulator, entries, index) + url = site_path(f"emulators/{emulator_card_page(emulator, anchor)}.md#{anchor}") name = str(entries[index].get("name", "")) for algorithm in HASH_ALGORITHMS: added.extend({ "value": value, "algorithm": algorithm, "layer": "emulator", "owner": emulator, "name": name, "url": url, "sha1": sha1, "declared": "name", - } for value in _hash_values(entry.get(algorithm))) + } for value in sorted_hash_values(entry.get(algorithm))) return added @@ -542,7 +543,7 @@ def _held_under_every_hash(records: list[dict], files: dict, indexes: dict) -> l for algorithm in HASH_ALGORITHMS: copies.extend({**record, "value": value, "algorithm": algorithm, "declared": record["algorithm"]} - for value in _hash_values(files[sha1].get(algorithm)) + for value in sorted_hash_values(files[sha1].get(algorithm)) if value != record["value"]) return copies @@ -587,6 +588,6 @@ def data_tree_pages(ref: str, members: dict[str, dict]) -> list[tuple[str, list[ if len(members) <= DATA_TREE_ROWS: return [] names = sorted(members) - stem = f"data-{_slugify_anchor(ref)}" + stem = f"data-{slugify_anchor(ref)}" return [(stem + (f"-{n}" if n > 1 else ""), names[start:start + DATA_TREE_ROWS_PER_PAGE]) for n, start in enumerate(range(0, len(names), DATA_TREE_ROWS_PER_PAGE), 1)] diff --git a/scripts/sitegen/measurements.py b/scripts/sitegen/measurements.py index b6b227180..7dd5bf051 100644 --- a/scripts/sitegen/measurements.py +++ b/scripts/sitegen/measurements.py @@ -34,10 +34,9 @@ from pathlib import Path from model import measurements as mr from sitegen import markup from core.artifacts import json_text, write_if_changed -from sitegen.render import _escape_tags +from sitegen.render import escape_tags from core.paths import REPO_ROOT -ROOT = REPO_ROOT REPO = "https://github.com/Abdess/retrobios" EXPLORER_PAGE = "measurements.md" METHOD_PAGE = "wiki/measurements.md" @@ -455,8 +454,8 @@ def records_commit(root: Path) -> str | None: return commit -def build(public: Path, root: Path = ROOT, emulators_dir: Path = ROOT / "emulators", - scratch: Path = ROOT / "tmp" / "site", system_names: dict[str, str] | None = None, +def build(public: Path, root: Path = REPO_ROOT, emulators_dir: Path = REPO_ROOT / "emulators", + scratch: Path = REPO_ROOT / "tmp" / "site", system_names: dict[str, str] | None = None, repo: str = REPO, commit: str | None = None) -> Built: """Write the index and the databases under the site's public folder. @@ -604,7 +603,7 @@ def _text(value: object) -> str: ends a sentence on the site: the record keeps the words as written.""" text = " ".join(str(value or "").split()) text = re.sub(r";\s+(\w)", lambda m: ". " + m[1].upper(), text) - return _escape_tags(text) + return escape_tags(text) def _short(commit: str | None) -> str: diff --git a/scripts/sitegen/nav.py b/scripts/sitegen/nav.py index bcc12c097..acf55e161 100644 --- a/scripts/sitegen/nav.py +++ b/scripts/sitegen/nav.py @@ -6,13 +6,13 @@ import re from collections.abc import Iterator from pathlib import Path -from model.collection import _slug +from model.collection import manufacturer_slug from model.composition import GAME_DATA_TOPS from model.guides import DEVICE_GROUPS, GROUP_TILES, HANDHELD_GUIDE from model.profiles import unique_emulator_profiles from sitegen import measurements as sitemeasurements, starlight as sitestarlight -from sitegen.config import _REPO_ROOT -from sitegen.decorate import _front_matter +from core.paths import REPO_ROOT +from sitegen.decorate import front_matter from sitegen.emulatorsindex import INITIAL_DIGITS, emulator_initial from sitegen.render import WIKI_SRC_DIR @@ -55,7 +55,7 @@ def _system_nav(manufacturers: dict) -> list: arcade: list[dict] = [] games: list[dict] = [] for mfr in sorted(manufacturers, key=str.casefold): - entry = {mfr: f"systems/{_slug(mfr)}.md"} + entry = {mfr: f"systems/{manufacturer_slug(mfr)}.md"} if mfr in GAME_DATA_TOPS: games.append(entry) else: @@ -117,12 +117,12 @@ def wiki_nav(wiki_dir: Path | None = None) -> dict[str, list[NavPlace]]: of its tab. `nav: false` keeps a page out on purpose. A page that says neither raises, naming what to add. """ - wiki_dir = Path(wiki_dir) if wiki_dir else _REPO_ROOT / WIKI_SRC_DIR + wiki_dir = Path(wiki_dir) if wiki_dir else REPO_ROOT / WIKI_SRC_DIR tabs: dict[str, list[NavPlace]] = {level: [] for level in TABS} for page in sorted(wiki_dir.glob("*.md")): where = f"{WIKI_SRC_DIR}/{page.name}" text = page.read_text(encoding="utf-8") - meta = _front_matter(text) + meta = front_matter(text) level = meta.get("level") if level not in TABS: raise NavError( @@ -152,7 +152,7 @@ def wiki_nav(wiki_dir: Path | None = None) -> dict[str, list[NavPlace]]: return tabs -def _overview_anchors(nav: list, docs: Path) -> dict[str, set[str]]: +def overview_anchors(nav: list, docs: Path) -> dict[str, set[str]]: """The heading ids of each overview page the navigation names, where a group of the sidebar finds its own section.""" def overviews(value: object) -> Iterator[str]: diff --git a/scripts/sitegen/pagemarkdown.py b/scripts/sitegen/pagemarkdown.py index c2a5cd43b..1645fd49b 100644 --- a/scripts/sitegen/pagemarkdown.py +++ b/scripts/sitegen/pagemarkdown.py @@ -374,17 +374,14 @@ def page_markdown(html: str, page_url: str) -> str: return converter.markdown() -ROOT = REPO_ROOT - - def build_stamp() -> dict[str, str]: """The commit the site is built from and its date. CI names the commit in GITHUB_SHA. The date is the commit's, so two builds of one commit write the same bytes.""" commit = os.environ.get("GITHUB_SHA") or subprocess.run( - ["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True, + ["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, capture_output=True, text=True, check=True).stdout.strip() - date = subprocess.run(["git", "log", "-1", "--format=%cI", commit], cwd=ROOT, + date = subprocess.run(["git", "log", "-1", "--format=%cI", commit], cwd=REPO_ROOT, capture_output=True, text=True, check=True).stdout.strip() return {"commit": commit, "date": date} diff --git a/scripts/sitegen/parts.py b/scripts/sitegen/parts.py index 315033301..45c40c84c 100644 --- a/scripts/sitegen/parts.py +++ b/scripts/sitegen/parts.py @@ -8,8 +8,8 @@ from pathlib import Path from core.paths import REPO_ROOT from sitegen import starlight as sitestarlight -from sitegen.config import _date_line -from sitegen.decorate import _front_matter +from sitegen.config import date_line +from sitegen.decorate import front_matter # A platform's file lists are split by the share of a page they render to, @@ -38,7 +38,7 @@ PUBLISHED_PARTS_FILE = (REPO_ROOT / "website" / "src" / "data" / "published-parts.json") -def _published_parts() -> dict[str, str]: +def load_published_parts() -> dict[str, str]: if not PUBLISHED_PARTS_FILE.is_file(): return {} return json.loads(PUBLISHED_PARTS_FILE.read_text(encoding="utf-8")) @@ -66,7 +66,7 @@ def record_parts(docs: Path, present: set[str], published: dict[str, str]) -> di if not page.is_file(): page = page.with_suffix(".mdx") try: - parent = _front_matter(page.read_text(encoding="utf-8")).get("parent") + parent = front_matter(page.read_text(encoding="utf-8")).get("parent") except OSError: continue if isinstance(parent, dict) and parent.get("link") and rel not in found: @@ -79,12 +79,12 @@ def record_parts(docs: Path, present: set[str], published: dict[str, str]) -> di LIST_PART_BUDGET = 300_000 -def _characters(lines: list[str]) -> int: +def character_count(lines: list[str]) -> int: return sum(len(line) + 1 for line in lines) -def _blocks_in_runs(blocks: list[list[str]], budget: int, - weigh: Callable[[list[str]], float] = _characters) -> list[list[str]]: +def blocks_in_runs(blocks: list[list[str]], budget: int, + weigh: Callable[[list[str]], float] = character_count) -> list[list[str]]: """Blocks (table rows, folded lists) in runs of at most ``budget``, by default in characters, a block never cut.""" runs: list[list[str]] = [[]] @@ -99,7 +99,7 @@ def _blocks_in_runs(blocks: list[list[str]], budget: int, return runs -def _parent_front_matter(parent: tuple[str, str] | None) -> list[str]: +def parent_front_matter(parent: tuple[str, str] | None) -> list[str]: """The `parent:` front matter of a part page: the page it belongs to, by label and site path, which the breadcrumb and sidebar read.""" if parent is None: @@ -108,7 +108,7 @@ def _parent_front_matter(parent: tuple[str, str] | None) -> list[str]: return ["parent:", f" label: {json.dumps(label)}", f" link: {json.dumps(link)}"] -def _list_pages( +def list_pages( stem: str, title: str, intro: str, head: list[str], blocks: list[list[str]], moved: dict[str, str], budget: int = LIST_PART_BUDGET, parent: tuple[str, str] | None = None, @@ -117,7 +117,7 @@ def _list_pages( opens each part, ``blocks`` are cut between parts. Returns where the list went, as the page it left says it. ``parent`` (label, site path) is the page the parts belong to, for the breadcrumb.""" - runs = _blocks_in_runs(blocks, budget) + runs = blocks_in_runs(blocks, budget) stems = [stem + (f"-{n}" if n > 1 else "") for n in range(1, len(runs) + 1)] for n, (here, run) in enumerate(zip(stems, runs), 1): part = f" (part {n} of {len(runs)})" if len(runs) > 1 else "" @@ -125,11 +125,11 @@ def _list_pages( # one read as duplicates to search and to validate_site. opening = f"Part {n} of {len(runs)}. {intro}" if len(runs) > 1 else intro moved[here] = "\n".join([ - "---", "level: reference", *_parent_front_matter(parent), "---", "", + "---", "level: reference", *parent_front_matter(parent), "---", "", f"# {title}{part}", "", opening, "", *([", ".join(f"[part {i}]({other}.md)" if other != here else f"part {i}" for i, other in enumerate(stems, 1)), ""] if len(runs) > 1 else []), - *head, *run, "", _date_line(), + *head, *run, "", date_line(), ]) + "\n" if len(stems) == 1: return f"[a page of their own]({stems[0]}.md)" diff --git a/scripts/sitegen/places.py b/scripts/sitegen/places.py index 9ae4fb5af..dd3c14d0e 100644 --- a/scripts/sitegen/places.py +++ b/scripts/sitegen/places.py @@ -4,7 +4,7 @@ from __future__ import annotations from dataclasses import dataclass -from model.collection import _copy_places, _slug +from model.collection import copy_places, manufacturer_slug from resolve.localfile import resolution_is_hash_exact, resolve_local_file from resolve.ownership import BUCKET_FOLDERS, names_manufacturer @@ -14,7 +14,7 @@ def _copies_by_path(db: dict) -> dict[str, set[tuple[str, str, str]]]: files = db.get("files", {}) return { str(files[sha1].get("path", "")): where - for sha1, where in _copy_places(db).items() + for sha1, where in copy_places(db).items() } @@ -73,23 +73,23 @@ def _folders_by_name(manufacturers: dict) -> dict[str, set[tuple[str, str]]]: nintendo-nes, nes and the NES folder normalize alike, as do sega-mastersystem and Sega/Master System. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id index: dict[str, set[tuple[str, str]]] = {} for mfr, consoles in manufacturers.items(): for console in consoles: spelled = console.lower().replace(" ", "-") for key in { - _norm_system_id(f"{_slug(mfr)}-{spelled}"), _norm_system_id(spelled) + norm_system_id(f"{manufacturer_slug(mfr)}-{spelled}"), norm_system_id(spelled) }: index.setdefault(key, set()).add((mfr, console)) return index def _folder_named(sys_id: str, by_name: dict[str, set[tuple[str, str]]]) -> tuple[str, str] | None: - from model.systems import _norm_system_id + from model.systems import norm_system_id - places = by_name.get(_norm_system_id(sys_id), set()) + places = by_name.get(norm_system_id(sys_id), set()) return next(iter(places)) if len(places) == 1 else None @@ -180,7 +180,7 @@ def _profile_system_pages( pages[sys_id] = console_norm[sys_id] -def _system_pages_from_data( +def system_pages_from_data( manufacturers: dict, coverages: dict, db: dict, diff --git a/scripts/sitegen/platformfiles.py b/scripts/sitegen/platformfiles.py index 40e2bea86..bbdea0d1c 100644 --- a/scripts/sitegen/platformfiles.py +++ b/scripts/sitegen/platformfiles.py @@ -9,29 +9,30 @@ import re import urllib.parse from model import siteinputs -from model.collection import _profiles_in, _profiles_on_disk +from model.collection import profiles_in, profiles_on_disk from model.profiles import upstream_profile_index from model.systemnames import system_name from sitegen import entries as siteentries, markup from sitegen.cards import SHORT_HASH -from sitegen.config import REPO_URL, _REPO_ROOT, _date_line -from sitegen.fields import _hash_spans, search_excluded +from sitegen.config import REPO_URL, date_line +from core.paths import REPO_ROOT +from sitegen.fields import hash_spans, search_excluded from sitegen.parts import ( PAGE_BYTES, PAGE_ELEMENTS, PLATFORM_PART_BUDGET, PLATFORM_REFERENCE_BUDGET, PLATFORM_SECTION_BUDGET, - _blocks_in_runs, - _characters, - _parent_front_matter, + blocks_in_runs, + character_count, + parent_front_matter, ) from sitegen.render import ( - _code, - _count, - _emulator_link, - _escape_tags, - _fmt_size, + code_span, + count_text, + emulator_link, + escape_tags, + fmt_size, card_page, console_href, ) @@ -56,14 +57,14 @@ def _system_heading_link(sys_id: str, prefix: str = "") -> str: writes. A system with no section of its own is named, never sent to the page a storage folder chose. """ - return f"{_system_named_link(sys_id, prefix)} {_escape_tags(sys_id)}" + return f"{_system_named_link(sys_id, prefix)} {escape_tags(sys_id)}" def _system_named_link(sys_id: str, prefix: str = "") -> str: """A system's name, linked to the section system_section gives.""" from sitegen.render import system_section - name = _escape_tags(system_name(sys_id)) + name = escape_tags(system_name(sys_id)) section = system_section(sys_id) if section is not None: slug, console = section @@ -71,11 +72,11 @@ def _system_named_link(sys_id: str, prefix: str = "") -> str: return name -def _emulator_named_link(key: str, prefix: str = "") -> str: +def emulator_named_link(key: str, prefix: str = "") -> str: """An emulator by the name its page carries, linked to that page. A profile with no page (an alias, a test) is named only.""" - profile = _profiles_on_disk().get(key, {}) - label = _escape_tags(str(profile.get("emulator") or key)) + profile = profiles_on_disk().get(key, {}) + label = escape_tags(str(profile.get("emulator") or key)) if profile.get("type") == "alias" or profile.get("role") == "test": return label return f"[{label}]({prefix}emulators/{key}.md)" @@ -99,17 +100,17 @@ def _served_line(f: dict, declared_sha1: str = "") -> str: label = "Served by" if f.get("status") == "ok" else "Held, not the declared hash" parts = path.split("/") if not sha1 or len(parts) < 3 or parts[0] != "bios": - return f"{label}: {_code(path)}" + return f"{label}: {code_span(path)}" # The card of that copy: every hash, provenance and the download. page = urllib.parse.quote(card_page(path, sha1)) - link = f"{label}: [{_code(path)}](../systems/{page}.md#sha1-{sha1[:12]})" + link = f"{label}: [{code_span(path)}](../systems/{page}.md#sha1-{sha1[:12]})" declared = {value.strip().lower() for value in declared_sha1.split(",")} return link if sha1 in declared else f"{link} (sha1 `{sha1[:8]}`)" def _launcher_refs(config: dict) -> dict[str, list[str]]: """Entry name, casefolded -> each launcher record that opens it, rendered.""" - from resolve.launchers import _names as launcher_names + from resolve.launchers import record_names as launcher_names from resolve.launchers import bound_launchers from sitegen.sources import launcher_ref_markdown, list_source @@ -121,7 +122,7 @@ def _launcher_refs(config: dict) -> dict[str, list[str]]: for record in bound_launchers(config): if not isinstance(record, dict) or not record.get("source_ref"): continue - text = (f"{_escape_tags(str(record.get('emulator', '')))} at " + text = (f"{escape_tags(str(record.get('emulator', '')))} at " f"{launcher_ref_markdown(source, str(record['source_ref']))}") for name in launcher_names(record): names = found.setdefault(name.rsplit("/", 1)[-1].casefold(), []) @@ -133,7 +134,7 @@ def _launcher_refs(config: dict) -> dict[str, list[str]]: UNPROVEN_TITLE = "Launcher records a config does not prove" -def _launcher_unproven_section(config: dict) -> list[str]: +def launcher_unproven_section(config: dict) -> list[str]: """The platform's launcher records resting on a config the code does not prove. A config file is proof only when the code installing it and the code @@ -147,9 +148,9 @@ def _launcher_unproven_section(config: dict) -> list[str]: return [] source = list_source(str(config.get("source") or "")) body = [ - f"- {_escape_tags(row['emulator'])}, `{_escape_tags(row['passes_to'] or row['kind'])}` " + f"- {escape_tags(row['emulator'])}, `{escape_tags(row['passes_to'] or row['kind'])}` " f"at {launcher_ref_markdown(source, row['source_ref'])}: " - f"{_escape_tags('; '.join(row['missing']))}" + f"{escape_tags('; '.join(row['missing']))}" for row in rows ] return ["", *markup.details("note", f"{UNPROVEN_TITLE} ({len(rows)})", body)] @@ -270,14 +271,14 @@ def _platform_file_row(f: dict, cfg_entry: dict, hash_type: str = "", facts: list[str] = [] # One code element per value: Recalbox lists accepted md5s joined by # commas, and each is a value a reader compares a dump with. - facts.extend(f"{alg.upper()}: {_hash_spans(hashes[alg])}" + facts.extend(f"{alg.upper()}: {hash_spans(hashes[alg])}" for alg in ("sha1", "md5", "crc32", "sha256") if hashes[alg]) # The size closes the hash lines: a line of its own was one more # element per row. if size and facts: - facts[-1] += f" ({_fmt_size(size)})" + facts[-1] += f" ({fmt_size(size)})" elif size: - facts.append(f"Size: {_fmt_size(size)}") + facts.append(f"Size: {fmt_size(size)}") if f.get("status") == "untested" and f.get("reason"): facts.append(_text_html(f"Not confirmed: {f['reason']}")) # Not every entry is firmware: the platform may list a game's data or a @@ -330,10 +331,10 @@ def _page_share(lines: list[str]) -> float: """The share of a page the lines render to, in thousandths: the rows are HTML already, so their length is their weight in bytes.""" return max(_element_weight(lines) * 1000 / PAGE_ELEMENTS, - _characters(lines) * 1000 / PAGE_BYTES) + character_count(lines) * 1000 / PAGE_BYTES) -def _render_platform_systems( +def render_platform_systems( by_system: dict, config_files: dict, emulator_files: dict | None, platform: tuple[str, str] | None = None, moved: dict[str, str] | None = None, config: dict | None = None, @@ -350,7 +351,7 @@ def _render_platform_systems( lines: list[str] = [] # Per-system detail sections (collapsible for large platforms) use_collapsible = len(by_system) > 10 - by_system_declared = _declared_by_system(config_files) + by_system_declared = declared_by_system(config_files) launched = _launcher_refs(config or {}) sections: list[dict] = [] @@ -358,11 +359,11 @@ def _render_platform_systems( ok_count = sum(1 for f in files if f["status"] == "ok") total = len(files) - sys_emus = _system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id)) + sys_emus = system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id)) anchor = sys_id.replace(" ", "-") head = [f"{ok_count}/{total} files verified"] if sys_emus: - emu_links = ", ".join(_emulator_named_link(e, "../") for e in sorted(sys_emus)) + emu_links = ", ".join(emulator_named_link(e, "../") for e in sorted(sys_emus)) head[-1] += "\\" head.append(f"Emulators: {emu_links}") head.append("") @@ -388,8 +389,8 @@ def _render_platform_systems( # Measured in the share of a page the list renders to. size = _page_share(body) if use_collapsible: - status_tag = "OK" if ok_count == total else _count(total - ok_count, "issue") - block = markup.details("note", f"{_count(total, 'file')} ({status_tag})", body) + status_tag = "OK" if ok_count == total else count_text(total - ok_count, "issue") + block = markup.details("note", f"{count_text(total, 'file')} ({status_tag})", body) while block and not block[-1]: block.pop() else: @@ -425,7 +426,7 @@ def _render_platform_systems( if moved is not None and platform and sys_id in own_page: key, display = platform runs = [sec["head"] + _platform_file_list(run, sec["has_path"], anchor) - for run in _blocks_in_runs([[row] for row in sec["rows"]], + for run in blocks_in_runs([[row] for row in sec["rows"]], PLATFORM_PART_BUDGET, _page_share)] stems = [f"{key}-{anchor}" + (f"-{n}" if n > 1 else "") for n in range(1, len(runs) + 1)] @@ -434,7 +435,7 @@ def _render_platform_systems( # A console query landed here with no way to the console's # own page: the list says whose it is first, linked. moved[stem] = "\n".join([ - "---", *_parent_front_matter((display, f"/platforms/{key}/")), "---", "", + "---", *parent_front_matter((display, f"/platforms/{key}/")), "---", "", f"# {display}: {system_name(sys_id)}{part}", "", f"{display}'s list for {_system_named_link(sys_id, '../')}. " f"Part of the [{display} page]({key}.md#{anchor}), whose other systems " @@ -445,12 +446,12 @@ def _render_platform_systems( for i, other in enumerate(stems, 1))] if len(runs) > 1 else []), "", "## Files", "", *markup.details("note", ROLE_LEGEND_TITLE, [ROLE_LEGEND]), *search_excluded(run), - "", _date_line(), + "", date_line(), ]) + "\n" # The count and status a folded system shows in its summary, # linked to the page that lists the files. - tag = "OK" if ok_count == total else _count(total - ok_count, "issue") - count = f"{_count(total, 'file')} ({tag})" + tag = "OK" if ok_count == total else count_text(total - ok_count, "issue") + count = f"{count_text(total, 'file')} ({tag})" lines.extend([ f"[{count}]({stems[0]}.md)" if len(stems) == 1 else f"{count}: " + ", ".join( f"[part {i}]({stem}.md)" for i, stem in enumerate(stems, 1)), @@ -465,10 +466,10 @@ def _render_platform_systems( # Platforms with an updated file published by export_native.py. -_EXPORTED: set[str] = set() +EXPORTED: set[str] = set() -def _platform_data_links(name: str) -> str: +def platform_data_links(name: str) -> str: """The platform's own data, machine-readable: the YAML transcribed from its upstream list, this page's JSON and the manifest the installer reads. @@ -479,8 +480,8 @@ def _platform_data_links(name: str) -> str: f"[YAML]({REPO_URL}/blob/main/platforms/{name}.yml)", f"[JSON](../api/v1/platforms/{name}.json)", ] - if (_REPO_ROOT / "install" / f"{name}.json").is_file(): - # The site's own copy, byte for byte (_publish_manifests). + if (REPO_ROOT / "install" / f"{name}.json").is_file(): + # The site's own copy, byte for byte (publish_manifests). links.append(f"[install manifest](../api/v1/manifests/{name}.json)") # The installed BIOS folder for clrmamepro and RomVault. links.append(f"[DAT](../downloads/dat/{name}.dat)") @@ -489,7 +490,7 @@ def _platform_data_links(name: str) -> str: def _site_profiles() -> dict[str, dict]: """Every emulator profile, read once for the citations of a page.""" - return _profiles_in(str(siteinputs.current().emulators), skip_aliases=True) + return profiles_in(str(siteinputs.current().emulators), skip_aliases=True) # Whose code a source reference cites, in one word: a platform page names @@ -550,7 +551,7 @@ def _category_evidence_md(evidence: dict, launched: list[str] | None = None) -> name = "the platform's launcher" refs = list(launched or []) else: - name = _emulator_link(reader["emulator"], "../") + name = emulator_link(reader["emulator"], "../") groups[bool(reader.get("runs_system"))].append( f"{name} ({', '.join(refs)})" if refs else f"{name} (by {reader['proof']})") if not reader.get("runs_system"): @@ -569,7 +570,7 @@ def _category_evidence_md(evidence: dict, launched: list[str] | None = None) -> # A core the site gives no page (a test core) is named, not linked. with_page = _profiles_with_page(str(siteinputs.current().emulators)) cores = ("cores examined: " + ", ".join( - _emulator_link(c, "../") if c in with_page else c for c in examined) + emulator_link(c, "../") if c in with_page else c for c in examined) if examined else "no core examined") if evidence.get("unsettled"): return f"No reader found, not settled: {evidence['unsettled']} ({cores})" @@ -587,7 +588,7 @@ def _profiles_by_core_name() -> dict[str, list[str]]: @functools.cache def _profiles_with_page(emulators_dir: str) -> frozenset[str]: """The profiles the site writes a page for: no alias, no test core.""" - profiles = _profiles_in(emulators_dir, skip_aliases=True) + profiles = profiles_in(emulators_dir, skip_aliases=True) return frozenset( k for k, v in profiles.items() if v.get("type") != "alias" and v.get("role") != "test" ) @@ -595,7 +596,7 @@ def _profiles_with_page(emulators_dir: str) -> frozenset[str]: @functools.cache def _core_names_in(emulators_dir: str) -> dict[str, list[str]]: - profiles = _profiles_in(emulators_dir, skip_aliases=True) + profiles = profiles_in(emulators_dir, skip_aliases=True) with_page = _profiles_with_page(emulators_dir) return { core: sorted(k for k in keys if k in with_page) @@ -610,20 +611,20 @@ def _core_name_links(cores: list[str]) -> list[str]: for core in cores: keys = [core] if core in index.get(core, []) else index.get(core, []) if keys: - links.extend(_emulator_link(k, "../") for k in keys) + links.extend(emulator_link(k, "../") for k in keys) else: links.append(f"`{core}`") return links -def _core_folders_section(name: str, config: dict) -> list[str]: +def core_folders_section(name: str, config: dict) -> list[str]: """Each folder the frontend hands a core, and the files the pack puts in it. For a platform that names no file of its own (MinUI and its forks): the folders come from its launch scripts, the files from its install manifest. """ folders = config.get("core_system_dirs") or {} - manifest = _REPO_ROOT / "install" / f"{name}.json" + manifest = REPO_ROOT / "install" / f"{name}.json" files = json.loads(manifest.read_text())["files"] if manifest.is_file() else [] lines = [ "### Core folders", @@ -646,7 +647,7 @@ def _core_folders_section(name: str, config: dict) -> list[str]: return lines -def _declared_by_system(config_files: dict) -> dict[str, list[dict]]: +def declared_by_system(config_files: dict) -> dict[str, list[dict]]: """The platform's own entries of each system, hashes included.""" by_system: dict[str, list[dict]] = {} for (sys_id, _name), entries in config_files.items(): @@ -654,7 +655,7 @@ def _declared_by_system(config_files: dict) -> dict[str, list[dict]]: return by_system -def _system_emulators( +def system_emulators( sys_id: str, emulator_files: dict | None, files: list[dict] | None = None ) -> list[str]: """The emulators a platform runs for one of its systems. @@ -666,9 +667,9 @@ def _system_emulators( an archive does not count: fbneo's boot.bin is read inside bubsys.zip, and RomM's Dreamcast boot.bin is not that file. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id - norm = _norm_system_id(sys_id) + norm = norm_system_id(sys_id) by_id = [name for name, data in (emulator_files or {}).items() if sys_id in data["systems"] or norm in data["norm"]] if by_id or not files: diff --git a/scripts/sitegen/platformindex.py b/scripts/sitegen/platformindex.py index 00fbff342..ee223bf63 100644 --- a/scripts/sitegen/platformindex.py +++ b/scripts/sitegen/platformindex.py @@ -7,7 +7,7 @@ from model.guides import DEVICE_GROUPS, GROUP_TILES, GUIDES from resolve.nativemode import check_label from sitegen import markup from sitegen.guidepage import NO_ZIP_FAQ -from sitegen.home import _group_members +from sitegen.home import group_members from sitegen.install import has_release_pack from sitegen.readme import release_totals @@ -27,7 +27,7 @@ def generate_platform_index(coverages: dict, registry: dict | None = None) -> st "", ] for group, (label, _description) in DEVICE_GROUPS.items(): - members = _group_members(coverages, registry, group) + members = group_members(coverages, registry, group) if not members: continue # The group label names the devices, and each card carries its diff --git a/scripts/sitegen/platformpage.py b/scripts/sitegen/platformpage.py index 5a9489a92..effabe384 100644 --- a/scripts/sitegen/platformpage.py +++ b/scripts/sitegen/platformpage.py @@ -9,25 +9,25 @@ from model.guides import GUIDES from model.systemnames import system_name from resolve.nativemode import check_label, reads_file_contents from sitegen import markup -from sitegen.config import REPO_URL, _date_line +from sitegen.config import REPO_URL, date_line from sitegen.decorate import level_label from sitegen.diagrams import local_images -from sitegen.guidepage import _pack_buttons, _platform_guide -from sitegen.home import _stat -from sitegen.install import _platform_install_block +from sitegen.guidepage import pack_buttons, platform_guide +from sitegen.home import stat_block +from sitegen.install import platform_install_block from sitegen.platformfiles import ( ROLE_LEGEND, ROLE_LEGEND_TITLE, - _EXPORTED, - _core_folders_section, - _declared_by_system, - _emulator_named_link, - _launcher_unproven_section, - _platform_data_links, - _render_platform_systems, - _system_emulators, + EXPORTED, + core_folders_section, + declared_by_system, + emulator_named_link, + launcher_unproven_section, + platform_data_links, + render_platform_systems, + system_emulators, ) -from sitegen.render import _escape_tags, _pct +from sitegen.render import escape_tags, percent_text # A hash a platform's list writes, in words. @@ -48,7 +48,7 @@ def _transcribed_row(config: dict) -> list[str]: note = " (a branch: the revision read is not recorded)" if moving else "" # Named in words: the raw URL broke into 25 lines of 8 characters # on a phone. - link = (f"[{_escape_tags(listed.label)}]({listed.browse()})" if listed + link = (f"[{escape_tags(listed.label)}]({listed.browse()})" if listed else f"<{transcribed}>") return [f"| Transcribed from | {link}{note} |"] @@ -73,9 +73,9 @@ def _platform_meta_rows(name: str, config: dict, mode: str, registry: dict) -> l if homepage: rows.append(f"| Homepage | [{homepage}]({homepage}) |") rows.extend(_transcribed_row(config)) - if name in _EXPORTED: + if name in EXPORTED: rows.append(f"| Updated file | [Download it and see the changes](../exports.md#{name}) |") - rows.append(f"| Data | {_platform_data_links(name)} |") + rows.append(f"| Data | {platform_data_links(name)} |") for cb in registry.get(name, {}).get("contributed_by", []) or []: username = cb.get("username", "") contribution = cb.get("contribution", "") @@ -92,17 +92,17 @@ def _platform_band(cov: dict) -> list[str]: """The coverage figures above a platform's detail card.""" config = cov["config"] mode = cov["mode"] - pct = _pct(cov["present"], cov["total"]) + pct = percent_text(cov["present"], cov["total"]) mode_badge = ( "rb-badge-success" if reads_file_contents(mode) else "rb-badge-info" ) return [ markup.block_open("div", 'class="rb-stats"'), "", - *_stat(f"{cov['present']}/{cov['total']}", f"Coverage ({pct})"), - *_stat(str(cov["verified"]), "Verified"), - *_stat(str(cov["missing"]), "Missing"), - *_stat(f'{check_label(mode, config.get("hash_rule"))}', + *stat_block(f"{cov['present']}/{cov['total']}", f"Coverage ({pct})"), + *stat_block(str(cov["verified"]), "Verified"), + *stat_block(str(cov["missing"]), "Missing"), + *stat_block(f'{check_label(mode, config.get("hash_rule"))}', "Checked by"), "", "", @@ -151,7 +151,7 @@ def _platform_head(name: str, cov: dict, registry: dict, no_list: bool) -> list[ lines += [summary + (f" [{display} website]({homepage})." if homepage else ""), ""] if name in GUIDES: - lines += _platform_guide(name, display, cov, registry, no_list) + lines += platform_guide(name, display, cov, registry, no_list) lines += [ "## Reference: every file by system { #reference-every-file-by-system }", "", @@ -200,15 +200,15 @@ def generate_platform_page( if name not in GUIDES: detect = (registry.get(name, {}).get("install") or {}).get("detect") or [] on_card = any(rule.get("method") == "card_marker" for rule in detect) - lines.extend(["", *_platform_install_block(name, display, on_card)]) - lines.extend(["", _pack_buttons(name, f"Download {display} Pack", display=display)]) + lines.extend(["", *platform_install_block(name, display, on_card)]) + lines.extend(["", pack_buttons(name, f"Download {display} Pack", display=display)]) lines.append("") config_files, by_system = _platform_declarations(cov) if no_list: - lines.extend(_core_folders_section(name, config)) - if _own_list_only(config): + lines.extend(core_folders_section(name, config)) + if own_list_only(config): lines.extend([f"**Cores:** {OWN_LIST_ONLY}", ""]) # System summary table (quick navigation) @@ -220,7 +220,7 @@ def generate_platform_page( "|--------|-------|--------|-----------|", ] ) - by_system_declared = _declared_by_system(config_files) + by_system_declared = declared_by_system(config_files) for sys_id, files in sorted(by_system.items()): ok_count = sum(1 for f in files if f["status"] == "ok") total = len(files) @@ -232,18 +232,18 @@ def generate_platform_page( f'' f'{non_ok} issue{"s" if non_ok > 1 else ""}' ) - sys_emus = _system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id)) + sys_emus = system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id)) anchor = sys_id.replace(" ", "-") # Named and linked as the detail blocks below do: the column held # profile ids, none of 1,463 linked. - emu_str = ", ".join(_emulator_named_link(e, "../") for e in sorted(sys_emus)[:3]) + emu_str = ", ".join(emulator_named_link(e, "../") for e in sorted(sys_emus)[:3]) if len(sys_emus) > 3: emu_str += f" [+{len(sys_emus) - 3}](#{anchor})" # The name a reader filters on, the id the list writes beside it. # The id and the count are no words a reader searches for: indexed, # every platform page answered a system id before its system's page. lines.append( - f"| [{_escape_tags(system_name(sys_id))}](#{anchor}) " + f"| [{escape_tags(system_name(sys_id))}](#{anchor}) " f"{sys_id} " f"| {ok_count}/{total} | {status} | {emu_str} |" ) @@ -252,12 +252,12 @@ def generate_platform_page( lines.extend(markup.details("note", ROLE_LEGEND_TITLE, [ROLE_LEGEND])) lines.extend( - _render_platform_systems(by_system, config_files, emulator_files, + render_platform_systems(by_system, config_files, emulator_files, (name, display), moved, config) ) - lines.extend(_launcher_unproven_section(config)) + lines.extend(launcher_unproven_section(config)) - lines.extend(["", _date_line()]) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" @@ -266,6 +266,6 @@ def generate_platform_page( OWN_LIST_ONLY = "None. Its own list is the whole truth: no core profile adds a file." -def _own_list_only(config: dict) -> bool: +def own_list_only(config: dict) -> bool: """The platform declares `cores: []`: its own list decides alone.""" return isinstance(config.get("cores"), list) and not config["cores"] diff --git a/scripts/sitegen/provenance.py b/scripts/sitegen/provenance.py index 747d5e8a1..d5a96ecfa 100644 --- a/scripts/sitegen/provenance.py +++ b/scripts/sitegen/provenance.py @@ -9,10 +9,10 @@ from datetime import datetime from model.composition import compute_composition, count_catalog_matched from acquire.provenance import distinct_missing from sitegen import entries as siteentries, markup -from sitegen.cards import _PROVENANCE_LABELS, _ROMSET_SOURCES -from sitegen.config import _date_line -from sitegen.parts import _list_pages -from sitegen.render import _count, _escape_tags, _slugify_anchor +from sitegen.cards import PROVENANCE_LABELS, ROMSET_SOURCES +from sitegen.config import date_line +from sitegen.parts import list_pages +from sitegen.render import count_text, escape_tags, slugify_anchor _PROVENANCE_HOMES = { @@ -46,7 +46,7 @@ def _date_in_words(stamp: str) -> str: try: day = datetime.strptime(str(stamp)[:10], "%Y-%m-%d") except ValueError: - return _escape_tags(str(stamp)) + return escape_tags(str(stamp)) return f'' @@ -62,7 +62,7 @@ def generate_provenance_page( total_files = compute_composition(db)["systems"]["files"] # When each catalog was read: a 76-day-old snapshot showed no age. as_of = ", ".join( - f"{_PROVENANCE_LABELS.get(source, source)} {_date_in_words(data['imported_at'])}" + f"{PROVENANCE_LABELS.get(source, source)} {_date_in_words(data['imported_at'])}" for source, data in report.items() if data.get("imported_at") ) @@ -120,7 +120,7 @@ def generate_provenance_page( ] for source, data in report.items(): - label = _PROVENANCE_LABELS.get(source, source) + label = PROVENANCE_LABELS.get(source, source) home = _PROVENANCE_HOMES.get(source, "") in_scope = data["matched"] + len(data["missing"]) pct = 100 * data["matched"] / in_scope if in_scope else 0 @@ -145,7 +145,7 @@ def generate_provenance_page( out_of_scope = {s: d["out_of_scope"] for s, d in report.items() if d["out_of_scope"]} if out_of_scope: detail = ", ".join( - f"{_PROVENANCE_LABELS.get(s, s)} {c:,}" for s, c in sorted(out_of_scope.items()) + f"{PROVENANCE_LABELS.get(s, s)} {c:,}" for s, c in sorted(out_of_scope.items()) ) lines.extend( [ @@ -187,7 +187,7 @@ def generate_provenance_page( lines.extend(_derivable_section(derived_entries, derivable)) - lines.extend(["", _date_line()]) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" @@ -224,7 +224,7 @@ def _wanted_dat_table(entries: list) -> list[str]: # Where an emulator's romset already carries the dump. for hit in entry.get("romsets", []): desc += ( - f" Ships in {_ROMSET_SOURCES.get(hit['source'], hit['source'])} " + f" Ships in {ROMSET_SOURCES.get(hit['source'], hit['source'])} " f"`{hit['archive']}` as `{hit['member']}`." ) table.append(f"| `{name}` | {desc} | `{sha1}` |") @@ -233,22 +233,22 @@ def _wanted_dat_table(entries: list) -> list[str]: def _wanted_section(source: str, data: dict, derived: int, moved: dict[str, str] | None) -> list[str]: """A catalog's missing dumps, by DAT, or a line naming the page they went to.""" - label = _PROVENANCE_LABELS.get(source, source) + label = PROVENANCE_LABELS.get(source, source) by_dat: dict[str, list] = {} for entry in data["missing"]: for dat in entry.get("dats") or [entry.get("dat", "")]: by_dat.setdefault(dat, []).append(entry) lines = [f"### {label}", ""] if moved is not None: - where = _list_pages( - f"provenance-{_slugify_anchor(source)}", f"Wanted from {label}", + where = list_pages( + f"provenance-{slugify_anchor(source)}", f"Wanted from {label}", f"Dumps {label} catalogues and the collection lacks. Part of " - f"[Dump provenance](provenance.md#{_slugify_anchor(label)}).", + f"[Dump provenance](provenance.md#{slugify_anchor(label)}).", [], [_wanted_list(source, label, data, by_dat, derived)], moved, parent=("Dump provenance", "/provenance/"), ) lines.extend([ - f"{_count(len(data['missing']), 'dump')} in {_count(len(by_dat), 'DAT')}: " + f"{count_text(len(data['missing']), 'dump')} in {count_text(len(by_dat), 'DAT')}: " f"listed on {where}.", "", ]) return lines @@ -293,10 +293,10 @@ def _wanted_list(source: str, label: str, data: dict, by_dat: dict[str, list], missing = data["missing"] held = data["matched"] reached = held + len(missing) + derived - dats = _count(len(data["covered_dats"]), "DAT") + dats = count_text(len(data["covered_dats"]), "DAT") lines = [ f"Held: **{held:,}** of {reached:,}, in the {dats} the collection reaches. " - f"Wanted: **{len(missing):,}**, from {_count(len(by_dat), 'DAT')}.", + f"Wanted: **{len(missing):,}**, from {count_text(len(by_dat), 'DAT')}.", "", ] if derived: @@ -315,7 +315,7 @@ def _wanted_list(source: str, label: str, data: dict, by_dat: dict[str, list], desc = markup.inline_html(entry.get("description") or "") for hit in entry.get("romsets", []): desc += markup.inline_html( - f" Ships in {_ROMSET_SOURCES.get(hit['source'], hit['source'])} " + f" Ships in {ROMSET_SOURCES.get(hit['source'], hit['source'])} " f"`{hit['archive']}` as `{hit['member']}`.") in_dats = ", ".join(html.escape(d) for d in (entry.get("dats") or [entry.get("dat", "")])) sha1 = html.escape(entry.get("sha1") or "-") @@ -333,10 +333,10 @@ def _wanted_list(source: str, label: str, data: dict, by_dat: dict[str, list], f'{sha1}') heads = ["Name", "DAT", "Description", "SHA1"] lines.extend([ - siteentries.filter_box(f"rb-wanted-filter-{_slugify_anchor(source)}", + siteentries.filter_box(f"rb-wanted-filter-{slugify_anchor(source)}", "dumps", heads, len(rows)), '
    ', - f"All {_count(len(rows), 'wanted dump')}", + f"All {count_text(len(rows), 'wanted dump')}", '', "" + "".join(f'' for h in heads) + "", "", *rows, "", "
    {h}
    ", "
    ", "", diff --git a/scripts/sitegen/publish.py b/scripts/sitegen/publish.py index 04c370f2a..61f4397e1 100644 --- a/scripts/sitegen/publish.py +++ b/scripts/sitegen/publish.py @@ -7,8 +7,8 @@ import shutil from pathlib import Path from model import releaserecord -from sitegen.config import _REPO_ROOT -from sitegen.write import _record, write_if_changed +from core.paths import REPO_ROOT +from sitegen.write import record_written, write_if_changed def write_release_advertised(generated: Path) -> None: @@ -26,7 +26,7 @@ def write_release_advertised(generated: Path) -> None: ) -def _publish_manifests(api: Path) -> list[tuple]: +def publish_manifests(api: Path) -> list[tuple]: """The install manifests and the release record, beside the API. The platform's list says what a setup checks. The manifest says what its @@ -38,34 +38,34 @@ def _publish_manifests(api: Path) -> list[tuple]: folder = api / "manifests" folder.mkdir(parents=True, exist_ok=True) assets: list[tuple] = [] - for source in sorted((_REPO_ROOT / "install").glob("*.json")): + for source in sorted((REPO_ROOT / "install").glob("*.json")): target = folder / source.name shutil.copy2(source, target) - _record(target) + record_written(target) assets.append((target, f"Install manifest: {source.stem}", "application/json", "schemas/install-manifest.schema.json")) # The target lists install.py --target reads: no catalog entry, and # api/v1/targets/ answered 404. targets = api / "targets" targets.mkdir(parents=True, exist_ok=True) - for source in sorted((_REPO_ROOT / "install" / "targets").glob("*.json")): + for source in sorted((REPO_ROOT / "install" / "targets").glob("*.json")): shutil.copy2(source, targets / source.name) - _record(targets / source.name) + record_written(targets / source.name) assets.append((targets / source.name, f"Target list: {source.stem}", "application/json", "schemas/target-manifest.schema.json")) # Every change each updated platform file carries, for a maintainer who # reviews them by script: the Exports page linked only the files. exports = api / "exports" exports.mkdir(parents=True, exist_ok=True) - for source in sorted((_REPO_ROOT / "exports").glob("*.json")): + for source in sorted((REPO_ROOT / "exports").glob("*.json")): shutil.copy2(source, exports / source.name) - _record(exports / source.name) + record_written(exports / source.name) assets.append((exports / source.name, f"Updated platform file, its changes: {source.stem}", "application/json", None)) - release = _REPO_ROOT / "release.json" + release = REPO_ROOT / "release.json" if release.is_file(): shutil.copy2(release, api / "release.json") - _record(api / "release.json") + record_written(api / "release.json") assets.append((api / "release.json", "Latest release: packs, sizes and assets", "application/json", "schemas/release.schema.json")) return assets diff --git a/scripts/sitegen/readme.py b/scripts/sitegen/readme.py index 88dc0b078..205542d54 100644 --- a/scripts/sitegen/readme.py +++ b/scripts/sitegen/readme.py @@ -122,11 +122,10 @@ def compute_coverage( } -_REPO = REPO_ROOT # The site and the README read the same coverage: the first generator to run # stores it here and the second reads it back, instead of verifying every # platform twice (about a minute of the site build). -COVERAGE_CACHE_DIR = _REPO / "tmp" / "coverage-cache" +COVERAGE_CACHE_DIR = REPO_ROOT / "tmp" / "coverage-cache" _COVERAGE_CACHE_FORMAT = "3" @@ -150,12 +149,12 @@ def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> s add_file(db_path.resolve()) for root, pattern in ((Path(platforms_dir), "*"), (Path(emulators_dir), "*.yml"), - (_REPO / "scripts", "*.py"), (_REPO / "install", "*.json"), - (_REPO / "recipes", "*.json")): + (REPO_ROOT / "scripts", "*.py"), (REPO_ROOT / "install", "*.json"), + (REPO_ROOT / "recipes", "*.json")): for path in sorted(p for p in root.resolve().rglob(pattern) if p.is_file()): add_file(path) - for path in (_REPO / ".gitignore", _REPO / "_mame_clones.json", - _REPO / "data" / ".versions.json"): + for path in (REPO_ROOT / ".gitignore", REPO_ROOT / "_mame_clones.json", + REPO_ROOT / "data" / ".versions.json"): add_file(path) digest.update(b"offline\0" + (b"1" if os.environ.get("RETROBIOS_OFFLINE") else b"0") + b"\n") large = Path(LARGE_FILES_CACHE).resolve() @@ -164,7 +163,7 @@ def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> s if path.is_file(): stat = path.stat() digest.update(f"{path.name}\0{stat.st_size}\0{stat.st_mtime_ns}\n".encode()) - bios = _REPO / "bios" + bios = REPO_ROOT / "bios" for path in sorted(bios.rglob("*")): if path.is_file(): stat = path.stat() @@ -205,7 +204,7 @@ def platform_coverages( else: if stored.get("platforms") == names: coverages = stored["coverages"] - print(f" coverage read from {cache.relative_to(_REPO)}") + print(f" coverage read from {cache.relative_to(REPO_ROOT)}") if coverages is None: coverages = {} for name in names: @@ -815,7 +814,7 @@ def ci_install_lines() -> tuple[str, str]: could pass on releases CI never installs. Read from the workflow, the two cannot disagree. The second line is the Python 3.8 one. """ - text = (_REPO / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") + text = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") main = re.search(r'^\s*run: (pip install pyyaml "jsonschema.*markdown.*)$', text, re.M) floor = re.search(r"^\s*run: (python3\.8 -m pip install .*)$", text, re.M) if main is None or floor is None: @@ -964,7 +963,7 @@ def generate_contributing() -> str: ) -def _write(readme: str) -> None: +def write_readme(readme: str) -> None: status = "Generated" if write_if_changed("README.md", readme) else "Unchanged" print(f"{status} ./README.md") diff --git a/scripts/sitegen/reference.py b/scripts/sitegen/reference.py index 685420985..f6d095835 100644 --- a/scripts/sitegen/reference.py +++ b/scripts/sitegen/reference.py @@ -5,14 +5,14 @@ from __future__ import annotations import json from model.profiles import unique_emulator_profiles -from sitegen.home import _next_block +from sitegen.home import next_block from sitegen.readme import contributing_text def generate_contributing() -> str: return contributing_text( lambda page: f"{page}.md", "# Contributing", "on this site" - ) + "\n" + "\n".join(_next_block([ + ) + "\n" + "\n".join(next_block([ "[Profiling an emulator](wiki/profiling.md), the first task most " "contributions start from", ])) @@ -45,7 +45,7 @@ def generate_not_found() -> str: def reference_next() -> str: - return "\n" + "\n".join(_next_block([ + return "\n" + "\n".join(next_block([ "[Reference index](wiki/index.md), every reference page in one list", "For contributors: [How to contribute](contributing.md)", ])) diff --git a/scripts/sitegen/render.py b/scripts/sitegen/render.py index fd08b74b9..61bebacaf 100644 --- a/scripts/sitegen/render.py +++ b/scripts/sitegen/render.py @@ -9,16 +9,16 @@ from collections.abc import Callable from model import siteinputs from sitegen import markup from core.paths import REPO_ROOT -from model.collection import _PROGRAM_TOPS, _card_moves, _slug +from model.collection import PROGRAM_TOPS, card_moves, manufacturer_slug from model.systemnames import ( SYSTEM_PARENTS, - _boards_built, - _console_anchors, - _ensure_console_sections, - _own_section, - _program_names, - _section_pairs, - _sections_by_name, + boards_built, + console_anchors, + ensure_console_sections, + own_section, + known_program_names, + section_pairs, + sections_by_name, system_name, ) @@ -34,7 +34,7 @@ _icon_available: dict[str, bool] = {} _CODE_SPAN = re.compile(r"(`+).+?\1", re.S) -def _code(value: object) -> str: +def code_span(value: object) -> str: """A value as an inline code span it cannot leave. Markdown shows HTML inside a code span as text, so the one way out is a @@ -44,12 +44,12 @@ def _code(value: object) -> str: return "`" + str(value).replace("`", "'") + "`" -def _count(number: int, noun: str, plural: str = "") -> str: +def count_text(number: int, noun: str, plural: str = "") -> str: """A count and its noun, singular for one: the site printed "1 files" 234 times.""" return f"{number:,} {noun if number == 1 else plural or noun + 's'}" -def _escape_tags(text: str) -> str: +def escape_tags(text: str) -> str: """Show a placeholder such as ```` as it was written. Profile prose names paths with angle brackets. Passed through as HTML @@ -70,12 +70,12 @@ def _escape_tags(text: str) -> str: return "".join(out) -def _admonition_body(text: str) -> str: +def admonition_body(text: str) -> str: """Indent prose without turning source tokens such as ``#if`` into H1s.""" - escaped = re.sub(r"(?m)^(\s*)#", r"\1\\#", _escape_tags(text)) + escaped = re.sub(r"(?m)^(\s*)#", r"\1\\#", escape_tags(text)) return escaped.replace("\n", "\n ") -def _icon_name(manufacturer: str, console_name: str) -> str: +def console_icon_name(manufacturer: str, console_name: str) -> str: return f"{manufacturer} - {console_name}".replace("/", " ") def _icon_url(icon_name: str) -> str: @@ -101,15 +101,15 @@ def system_icon_markdown(manufacturer: str, console_name: str) -> str: The link names the upstream file: ``sitediagrams.localize_images`` points it at the local copy, whose source is recorded beside it. """ - name = _icon_name(manufacturer, console_name) + name = console_icon_name(manufacturer, console_name) if not _icon_available.get(name): return "" return markup.image(console_name, _icon_url(name), width="24") + " " # Global index: maps system_id -> (manufacturer_slug, console_name) for cross-linking -_system_page_map: dict[str, tuple[str, str]] = {} +system_page_map: dict[str, tuple[str, str]] = {} -def _slugify_anchor(text: str) -> str: +def slugify_anchor(text: str) -> str: """Slugify text for MkDocs anchor compatibility.""" import re @@ -129,29 +129,29 @@ def set_system_page_map(mapping: dict[str, tuple[str, str]]) -> None: derived from it here. Kept anywhere else, it outlived a table of the same size and linked to the pages of the previous one. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id - _system_page_map.clear() - _system_page_map.update(mapping) + system_page_map.clear() + system_page_map.update(mapping) _norm_page_map.clear() - for known, page in _system_page_map.items(): - key = _norm_system_id(known) + for known, page in system_page_map.items(): + key = norm_system_id(known) if _norm_page_map.get(key, page) != page: _norm_page_map[key] = None else: _norm_page_map[key] = page -def _page_by_norm(sys_id: str) -> tuple[str, str] | None: +def page_by_norm(sys_id: str) -> tuple[str, str] | None: """The page an id leads to under another spelling of the same system. Emulator cards name sega-megadrive or sinclair-zxspectrum, the pages are keyed by the platforms' spellings: 2,431 of 4,195 cards had no link. A spelling two pages share leads nowhere rather than to either. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id - return _norm_page_map.get(_norm_system_id(sys_id)) + return _norm_page_map.get(norm_system_id(sys_id)) # A manufacturer page too large for one page is a summary, each console on @@ -189,8 +189,8 @@ def console_anchor(manufacturer: str, console: str) -> str: """The id of a console's heading on its manufacturer's page.""" from core.anchors import toc_slug - key = (_slug(manufacturer), console) - return _console_anchors.get(key) or toc_slug(console) + key = (manufacturer_slug(manufacturer), console) + return console_anchors.get(key) or toc_slug(console) def console_href(slug: str, console: str, prefix: str = "") -> str: @@ -219,7 +219,7 @@ def card_page(path: str, sha1: str) -> str: board = arcade_board(sha1) if board in _board_sections: return f"arcade-{board_slug(board)}" - slug, console = _card_moves.get((slug, console, str(sha1)), (slug, console)) + slug, console = card_moves.get((slug, console, str(sha1)), (slug, console)) return _card_pages.get((slug, console, sha1), slug) @@ -268,25 +268,25 @@ def system_section(sys_id: str) -> tuple[str, str] | None: def _section_without_boards(sys_id: str) -> tuple[str, str] | None: """system_section before arcade boards: what the folders and the reviewed parents give.""" - own = _own_section(sys_id) + own = own_section(sys_id) if own is not None: - return _slug(own[0]), own[1] + return manufacturer_slug(own[0]), own[1] parent = SYSTEM_PARENTS.get(sys_id) - if parent is not None and parent in _section_pairs: - return _slug(parent[0]), parent[1] + if parent is not None and parent in section_pairs: + return manufacturer_slug(parent[0]), parent[1] try: name = system_name(sys_id) except KeyError: return None - places = _sections_by_name.get(name.casefold(), set()) + places = sections_by_name.get(name.casefold(), set()) if len(places) != 1: return None mfr, console = next(iter(places)) if mfr in _NAMELESS_TOPS or ( - mfr in _PROGRAM_TOPS and console.casefold() in _program_names + mfr in PROGRAM_TOPS and console.casefold() in known_program_names ): return None - return _slug(mfr), console + return manufacturer_slug(mfr), console def _system_link(sys_id: str, prefix: str = "") -> str: @@ -319,7 +319,7 @@ def set_arcade_boards(profiles: dict[str, dict], db: dict) -> None: """Install the profiles and database the arcade boards are read from. Without it they are read from the repository on first use.""" _arcade_source[0] = (profiles, db) - _boards_built[0] = False + boards_built[0] = False def _owner_ids(entry: dict, systems: list[str]) -> set[str]: @@ -379,16 +379,16 @@ def _arcade_suffix_sha1s(db: dict) -> frozenset[str]: def _build_boards() -> None: - if _boards_built[0]: + if boards_built[0]: return - _ensure_console_sections() + ensure_console_sections() source = _arcade_source[0] if source is None: source = _read_arcade_source() if source is None: _archive_boards.clear() _board_names.clear() - _boards_built[0] = True + boards_built[0] = True return _arcade_source[0] = source profiles, db = source @@ -413,7 +413,7 @@ def _build_boards() -> None: archives = _entry_archives(entry, files, by_name) _cast_votes(key, entry, owners, archives, votes, ids_by_name) _elect_boards(votes, ids_by_name, db) - _boards_built[0] = True + boards_built[0] = True def _read_arcade_source() -> tuple[dict, dict] | None: @@ -450,7 +450,7 @@ def _entry_archives(entry: dict, files: dict, by_name: dict) -> set[str]: if sha1 not in files: continue if crcs: - held = zip_member_crcs(str(_REPO_ROOT / files[sha1]["path"])) + held = zip_member_crcs(str(REPO_ROOT / files[sha1]["path"])) # An archive the build cannot read keeps its name. if held and not held & crcs: continue @@ -514,7 +514,7 @@ def _machine_section(sys_id: str) -> tuple[str, str] | None: of the folder holding it: an id with a section of its own keeps its archives where the collection files them.""" parent = SYSTEM_PARENTS.get(sys_id) - if parent is None or parent[0] == "Arcade" or parent not in _section_pairs: + if parent is None or parent[0] == "Arcade" or parent not in section_pairs: return None return parent @@ -589,7 +589,7 @@ def arcade_boards() -> dict[str, str]: return {board: system_name(board) for board in sorted(set(_board_names.values()))} -def _field_text(key: object, value: object) -> str: +def scalar_text(key: object, value: object) -> str: """A scalar of a structured block. A source reference reads as code.""" if isinstance(value, bool): text = "yes" if value else "no" @@ -611,9 +611,9 @@ def _field_label(key: object) -> str: FieldText = Callable[[object, object], str] -def _render_yaml_value( +def render_yaml_value( lines: list[str], val: object, indent: int = 4, - field_text: FieldText = _field_text, + field_text: FieldText = scalar_text, ) -> None: """Render any YAML value as a nested markdown list. @@ -628,7 +628,7 @@ def _render_yaml_value( if isinstance(v, (dict, list)) and v: lines.append(f"{pad}- **{_field_label(k)}:**") lines.append("") - _render_yaml_value(lines, v, indent + 4, field_text) + render_yaml_value(lines, v, indent + 4, field_text) else: lines.append(f"{pad}- **{_field_label(k)}:** {field_text(k, v)}") lines.append("") @@ -645,7 +645,7 @@ def _render_yaml_value( lines.append(f"{pad}- {', '.join(parts)}".rstrip()) if nested: lines.append("") - _render_yaml_value(lines, nested, indent + 4, field_text) + render_yaml_value(lines, nested, indent + 4, field_text) else: lines.append(f"{pad}- {field_text(None, item)}") lines.append("") @@ -659,11 +659,11 @@ def _platform_link(name: str, display: str, prefix: str = "") -> str: """Generate a markdown link to a platform page.""" return f"[{display}]({prefix}platforms/{name}.md)" -def _emulator_link(name: str, prefix: str = "") -> str: +def emulator_link(name: str, prefix: str = "") -> str: """Generate a markdown link to an emulator page.""" return f"[{name}]({prefix}emulators/{name}.md)" -def _fmt_size(size: int) -> str: +def fmt_size(size: int) -> str: if size >= 1024 * 1024 * 1024: return f"{size / (1024**3):.1f} GB" if size >= 1024 * 1024: @@ -672,12 +672,12 @@ def _fmt_size(size: int) -> str: return f"{size / 1024:.1f} KB" return f"{size} B" -def _pct(n: int, total: int) -> str: +def percent_text(n: int, total: int) -> str: if total == 0: return "0%" return f"{n / total * 100:.1f}%" -def _by_mode(value: str | dict, mode: str) -> str: +def by_mode(value: str | dict, mode: str) -> str: """Read a profile field that may be keyed by build mode.""" if isinstance(value, dict): return str(value.get(mode) or "") if mode else "" @@ -689,9 +689,6 @@ def _by_mode(value: str | dict, mode: str) -> str: _NAMELESS_TOPS = frozenset({"Other"}) -_REPO_ROOT = REPO_ROOT - - # A system id that names a family of arcade boards -> the board its link # leads to. RetroArch's sega-dreamcast-arcade lists the NAOMI, NAOMI 2 and # Atomiswave BIOS: the NAOMI page comes first, the Dreamcast section links diff --git a/scripts/sitegen/sources.py b/scripts/sitegen/sources.py index f5fc5ace8..904eda8df 100644 --- a/scripts/sitegen/sources.py +++ b/scripts/sitegen/sources.py @@ -14,15 +14,15 @@ from pathlib import Path from core import upstream from core.paths import REPO_ROOT from model.sourceref import ( - _HEX_ADDRESS_RE, - _prose_runs, + HEX_ADDRESS_RE, + prose_runs, is_binary_citation, ref_annotation, ref_role, source_ref_values, split_source_ref, ) -from sitegen.render import _by_mode, _escape_tags +from sitegen.render import by_mode, escape_tags def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, str]]: @@ -44,8 +44,8 @@ def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, st return [ ( str(raw), - _by_mode(pin_field, label), - _by_mode(source_field, label), + by_mode(pin_field, label), + by_mode(source_field, label), ) ] @@ -55,7 +55,7 @@ def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, st key for key in raw if key != label ] return [ - (str(raw[key]), _by_mode(pin_field, key), _by_mode(source_field, key)) + (str(raw[key]), by_mode(pin_field, key), by_mode(source_field, key)) for key in ordered if raw.get(key) ] @@ -70,7 +70,7 @@ _BROWSE_ONLY = { } -def _browse_repo(url: str) -> upstream.Repo | None: +def browse_repo(url: str) -> upstream.Repo | None: """The repository a profile URL names, on any forge the pages can link. Profiles pinned on SourceForge, voidpoint.io, Bitbucket or Software @@ -109,7 +109,7 @@ def _forge_sources(profile: dict, label: str = "") -> list[tuple[upstream.Repo, for field in ("source", "upstream"): for value, pin, fallback in _repo_pins(profile, field, label): - repo = _browse_repo(value) + repo = browse_repo(value) if repo is None: continue repo_key = (repo.host, repo.slug) @@ -125,7 +125,7 @@ def _forge_sources(profile: dict, label: str = "") -> list[tuple[upstream.Repo, source_repos.add(repo_key) return candidates -def _source_permalink(repo: upstream.Repo, pin: str, path: str, +def source_permalink(repo: upstream.Repo, pin: str, path: str, start: int | None, end: int | None) -> str: """Forge-specific browser URL for one file at one immutable revision.""" quoted_path = urllib.parse.quote(path, safe="/@:+-._~") @@ -256,7 +256,7 @@ def cited_paths(profile: dict) -> set[str]: for _label, refs in source_ref_values(value): paths.update(ref_role(part.path)[1] for part in split_source_ref(refs)) elif isinstance(value, str) and ":" in value: - for _n, _span, _spans, parts, _run, _wrapped in _prose_runs(value): + for _n, _span, _spans, parts, _run, _wrapped in prose_runs(value): paths.update(part.path for part in parts) return {path for path in paths if _PATH_RE.fullmatch(path) and not is_binary_citation(path)} @@ -338,7 +338,7 @@ def build_files(profile: dict) -> list[tuple[upstream.Repo, str, str]]: revision, path). A tag can move, so a build read at a tag is not linked.""" found = [] for build in profile.get("pin_build") or []: - repo = _browse_repo(str(build.get("repo", ""))) + repo = browse_repo(str(build.get("repo", ""))) revision = str(build.get("revision", "")) if repo is not None and re.fullmatch(r"[0-9a-f]{40}", revision): found.append((repo, revision, str(build.get("path", "")))) @@ -392,14 +392,14 @@ def version_basis_url(profile: dict, basis: dict, mode: str = "") -> str: """ field = "upstream" if basis.get("repo") == "upstream" else "source" declared = next(iter(_repo_pins(profile, field, mode)), None) - repo = _browse_repo(declared[0]) if declared else None + repo = browse_repo(declared[0]) if declared else None if repo is None: return "" kind, path, tag = basis.get("kind"), str(basis.get("path") or ""), str(basis.get("tag") or "") if kind == "file" and path: pin = next((p for r, p in _forge_sources(profile, mode) if (r.host, r.slug) == (repo.host, repo.slug)), "") - return _source_permalink(repo, pin, path, None, None) if pin and tree_holds( + return source_permalink(repo, pin, path, None, None) if pin and tree_holds( repo, pin, path) else "" if kind == "tag" and tag and repo.family in ("github", "gitlab"): tree = "/-/tree/" if repo.family == "gitlab" else "/tree/" @@ -449,7 +449,7 @@ def role_sources(profile: dict, label: str = "") -> dict[str, tuple[upstream.Rep found: dict[str, tuple[upstream.Repo, str]] = {} for field in ("source", "upstream"): for value, pin, _fallback in _repo_pins(profile, field, label): - repo = _browse_repo(value) + repo = browse_repo(value) if repo is not None and pin and field not in found: found[field] = (repo, pin) return found @@ -475,7 +475,7 @@ def _two_repositories(profile: dict) -> bool: return bool(source and upstream_url and source != upstream_url) -def _source_ref_markdown(profile: dict, value: str | dict | None) -> str: +def source_ref_markdown(profile: dict, value: str | dict | None) -> str: """Render source_ref values as pinned links when their forge is known. Each part is followed by whose code it cites, in words, when the profile @@ -551,7 +551,7 @@ def source_ref_items(profile: dict, value: str | dict | None) -> list[tuple[str, rendered.append((f"`{display}`{note}", role)) else: repo, pin = selected - url = _source_permalink( + url = source_permalink( repo, pin, real_path, part.start, part.end ) rendered.append((f"[`{display}`]({url}){note}", role)) @@ -568,7 +568,7 @@ def _annotation_markdown(text: str) -> str: """ if not text: return "" - return " " + _escape_tags(re.sub(r"([*|\\])", r"\\\1", text)) + return " " + escape_tags(re.sub(r"([*|\\])", r"\\\1", text)) def _binary_citation(path: str, previous: str) -> tuple[str, str]: @@ -578,7 +578,7 @@ def _binary_citation(path: str, previous: str) -> tuple[str, str]: ranges of one library: the bare address continues the binary before it. No revision of a repository holds those bytes, so nothing is linked. """ - found = _HEX_ADDRESS_RE.search(path) + found = HEX_ADDRESS_RE.search(path) if found is None: return f"`{path}`", path binary = path[:found.start()].rstrip(" :") or previous @@ -614,7 +614,7 @@ def link_prose_citations(profile: dict, text: str) -> str: for line in text.split("\n"): guarded = _guarded_spans(line) edits = [] - for _n, path_span, spans, parts, _run, wrapped in _prose_runs(line): + for _n, path_span, spans, parts, _run, wrapped in prose_runs(line): path = parts[0].path if wrapped or " " in path or not _PATH_RE.fullmatch(path): continue @@ -631,7 +631,7 @@ def link_prose_citations(profile: dict, text: str) -> str: repo, pin = holders[0] for index, ((lo, hi), part) in enumerate(zip(spans, parts)): start = path_span[0] if index == 0 else lo - url = _source_permalink(repo, pin, part.path, part.start, part.end) + url = source_permalink(repo, pin, part.path, part.start, part.end) edits.append((start, hi, f"[`{line[start:hi]}`]({url})")) for start, end, link in sorted(edits, reverse=True): line = line[:start] + link + line[end:] diff --git a/scripts/sitegen/starlight.py b/scripts/sitegen/starlight.py index 1de2b9ce6..53a82fdf6 100644 --- a/scripts/sitegen/starlight.py +++ b/scripts/sitegen/starlight.py @@ -21,7 +21,7 @@ from html import unescape from pathlib import Path, PurePosixPath from core.paths import REPO_ROOT -from core.anchors import _unique, toc_slug +from core.anchors import unique_anchor, toc_slug BASE = "/retrobios/" SITE_URL = "https://abdess.github.io/retrobios/" @@ -145,14 +145,14 @@ def pin_heading_ids(text: str, title_id: str = "") -> str: tokens = attrs["attrs"].split() if attrs else [] if any(token.startswith("#") for token in tokens): return match.group(0) - ident = _unique(toc_slug(body), used) + ident = unique_anchor(toc_slug(body), used) return f"{match['hashes']} {body.rstrip()} {{ {' '.join(['#' + ident, *tokens])} }}" def raw(match: re.Match) -> str: if ID_ATTR.search(match["attrs"]): return match.group(0) level, text = match["level"], match["htmltext"] - ident = _unique(toc_slug(text), used) + ident = unique_anchor(toc_slug(text), used) return f'{text}' def pick(match: re.Match) -> str: @@ -434,7 +434,7 @@ def page_aliases(rel: str) -> list[str]: from sitegen import render as siterender by_page: dict[str, set[str]] = {} - for sys_id in list(siterender._system_page_map): + for sys_id in list(siterender.system_page_map): section = siterender.system_section(sys_id) names = siterender.system_search_aliases(sys_id) if not section or not names: @@ -444,7 +444,7 @@ def page_aliases(rel: str) -> list[str]: _page_aliases.clear() _page_aliases.update({page: sorted(names, key=str.casefold) for page, names in by_page.items()}) - _page_aliases_built[0] = bool(siterender._system_page_map) + _page_aliases_built[0] = bool(siterender.system_page_map) return list(_page_aliases.get(rel, [])) diff --git a/scripts/sitegen/startwith.py b/scripts/sitegen/startwith.py index 16c693a3a..49b966e3a 100644 --- a/scripts/sitegen/startwith.py +++ b/scripts/sitegen/startwith.py @@ -9,26 +9,26 @@ from dataclasses import dataclass from model.collection import SECTION_LABELS from packs.crossref import FileConsumers from sitegen import markup -from sitegen.cards import ROMSET_FAQ, _emulator_display, _romset_releases +from sitegen.cards import ROMSET_FAQ, emulator_display, romset_releases from sitegen.consolecards import ( Card, START_WITH_NAMES, - _Item, - _NO_PRIORITY, - _add_name, - _card_rank, - _entries_by_section, - _entry_systems, - _reading_pairs, - _region_order, - _setup_name, - _visible, - _without_files, + Item, + NO_PRIORITY, + add_name, + card_rank, + entries_by_section, + entry_systems, + reading_pairs, + region_order, + setup_name, + visible_name, + without_files, ) -from sitegen.descriptions import _said_as_list -from sitegen.emulatorcards import _region_words +from sitegen.descriptions import said_as_list +from sitegen.emulatorcards import region_words from sitegen.install import comes_with_app -from sitegen.render import _code, _count, console_anchor +from sitegen.render import code_span, count_text, console_anchor class _StartGroup: @@ -63,13 +63,13 @@ class _StartGroup: self.extras: set[tuple[str, str]] = set() def require(self, name: str, emulator: str) -> None: - self.written.setdefault(_visible(name), name) - self.requires.setdefault(_visible(name), set()).add(emulator) + self.written.setdefault(visible_name(name), name) + self.requires.setdefault(visible_name(name), set()).add(emulator) def read_for(self, line: str, name: str, emulator: str, read: str, card: str) -> None: """Record that ``emulator`` requires ``name`` for ``line``, under the name ``read``, its card titled ``card``.""" - visible = _visible(name) + visible = visible_name(name) self.line_readers.setdefault(line, {}).setdefault(visible, set()).add(emulator) self.read_as.setdefault((line, visible, emulator), read) self.card_names.setdefault((line, visible), card) @@ -77,11 +77,11 @@ class _StartGroup: def absorb(self, other: _StartGroup) -> None: for region, names in other.by_region.items(): for name in names: - _add_name(self.by_region.setdefault(region, []), name) + add_name(self.by_region.setdefault(region, []), name) for mine, theirs in ((self.plain, other.plain), (self.optional, other.optional), (self.extra, other.extra), (self.emulators, other.emulators)): for name in theirs: - _add_name(mine, name) + add_name(mine, name) for visible, emulators in other.requires.items(): self.written.setdefault(visible, other.written[visible]) self.requires.setdefault(visible, set()).update(emulators) @@ -112,13 +112,13 @@ class _StartGroup: continue reads = {self.read_as[(key, visible, e)] for e in emulators if (key, visible, e) in self.read_as} - written = self.written.get(visible, _code(card)) + written = self.written.get(visible, code_span(card)) # A linked name (a file under Arcade) keeps its link. - shown = written if _visible(written) == card else _code(card) + shown = written if visible_name(written) == card else code_span(card) if len(reads) == 1 and next(iter(reads)) != card: - return f"{shown} (as {_code(next(iter(reads)))})" + return f"{shown} (as {code_span(next(iter(reads)))})" return shown - return self.written.get(visible, _code(visible)) + return self.written.get(visible, code_span(visible)) _Read = tuple[str, dict, "str | None"] @@ -137,11 +137,11 @@ def _section_reads( kept: dict[str, list[_Read]] = {} for f in primaries: sha1 = str(f.get("sha1", "")) - for emulator, entry in _reading_pairs(sha1, consumers): + for emulator, entry in reading_pairs(sha1, consumers): if comes_with_app(entry): continue system = None - systems = _entry_systems(emulator, entry) + systems = entry_systems(emulator, entry) if here is not None and systems: system = next((s for s in systems if system_section(s) == here), None) if system is None: @@ -150,7 +150,7 @@ def _section_reads( candidates = list(primaries) known = (getattr(consumers, "_db", None) or {}).get("files", {}) if here is not None: - for sha1, emulator, entry, system in _entries_by_section(consumers).get(here, []): + for sha1, emulator, entry, system in entries_by_section(consumers).get(here, []): record = known.get(sha1) parts = str((record or {}).get("path", "")).split("/") if (sha1 in held or not record or comes_with_app(entry) or ".variants" in parts @@ -173,14 +173,14 @@ class _SectionReads: for f in ranked: sha1 = str(f.get("sha1", "")) pairs = kept.get(sha1, []) - name = _code(_setup_name(f, consumers, [(e, entry) for e, entry, _s in pairs])) + name = code_span(setup_name(f, consumers, [(e, entry) for e, entry, _s in pairs])) if f.get("elsewhere"): name = f"[{name}]({markup.site_href(f'files/?sha1={sha1}')})" self.rendered[sha1] = name # A member read inside its archive is the archive's to name: FinalBurn # Neo reads sfix.sfix inside neogeo.zip, and the line had it read # sfix.sfix instead of neogeo.zip. - self.archives = {_visible(name): (name, sha1) + self.archives = {visible_name(name): (name, sha1) for sha1, name in reversed(self.rendered.items())} db = getattr(consumers, "_db", None) or {} self.known = db.get("files", {}) @@ -195,8 +195,8 @@ class _SectionReads: found = [found] if isinstance(found, str) else sorted(found) found.sort(key=lambda s: "/.variants/" in str(self.known.get(s, {}).get("path", ""))) if not found: - return _code(archive), "" - return f"[{_code(archive)}]({markup.site_href(f'files/?sha1={found[0]}')})", "" + return code_span(archive), "" + return f"[{code_span(archive)}]({markup.site_href(f'files/?sha1={found[0]}')})", "" def reading(self, f: dict) -> Iterator[tuple[str, dict, str | None, str, str]]: """Each read of a file: the emulator, its entry, the system, the @@ -223,7 +223,7 @@ def _weak_starts(ranked: list[dict], reads: _SectionReads) -> tuple[dict[str, se if entry.get("hle_fallback"): continue side = requiring if entry.get("required", True) else optional - side.setdefault(named or _visible(name), set()).add(emulator) + side.setdefault(named or visible_name(name), set()).add(emulator) needs_other = {emulator: {key for key, emulators in requiring.items() if emulator in emulators} for emulators in requiring.values() for emulator in emulators} weak = {key for key, emulators in requiring.items() @@ -251,10 +251,10 @@ def _chosen_members(ranked: list[dict], reads: _SectionReads, for emulator, entry, _system, name, named in reads.reading(f): place = _group_place(emulator, entry) if place is not None: - member = named or _visible(name) + member = named or visible_name(name) rank = (-len(requiring.get(member, ())), - entry["priority"] if isinstance(entry.get("priority"), int) else _NO_PRIORITY, - _visible(name)) + entry["priority"] if isinstance(entry.get("priority"), int) else NO_PRIORITY, + visible_name(name)) members.setdefault(place, []).append((rank, member)) return {place: min(found)[1] for place, found in members.items()} @@ -265,25 +265,25 @@ def _add_start_read(group: _StartGroup, f: dict, read_by: tuple[str, dict, str, emulator, its entry, the name the line writes and the card's sha1.""" emulator, entry, name, named = read_by if named: - group.sha1s.setdefault(_visible(name), named) + group.sha1s.setdefault(visible_name(name), named) if emulator not in group.emulators: group.emulators.append(emulator) if entry.get("hle_fallback"): - _add_name(group.optional, name) + add_name(group.optional, name) group.hle.add(emulator) return if not entry.get("required", True): - _add_name(group.extra, name) + add_name(group.extra, name) return group.require(name, emulator) - read = str(entry.get("archive") or entry.get("name") or _visible(name)) + read = str(entry.get("archive") or entry.get("name") or visible_name(name)) card = str(entry["archive"]) if entry.get("archive") else str(f["name"]) regions = sorted({str(r) for r in entry.get("region") or []}) for region in regions or [""]: - _add_name(group.by_region.setdefault(region, []) if region else group.plain, name) + add_name(group.by_region.setdefault(region, []) if region else group.plain, name) group.read_for(region, name, emulator, read, card) - if (named or _visible(name)) in weak: - group.extras.add((region, _visible(name))) + if (named or visible_name(name)) in weak: + group.extras.add((region, visible_name(name))) def _start_groups( @@ -301,14 +301,14 @@ def _start_groups( the Mega CD BIOS for its Genesis), and one under Other is a single emulator's, its shaders and fonts. A file the emulator ships with is no file to fetch.""" - from model.systemnames import _heading_name, system_name - from model.collection import _slug + from model.systemnames import heading_name, system_name + from model.collection import manufacturer_slug - here = (_slug(section[0]), section[1]) if section else None + here = (manufacturer_slug(section[0]), section[1]) if section else None kept, candidates = _section_reads(files, consumers, here) groups: dict[str | None, _StartGroup] = {} - ranked = sorted(candidates, key=lambda f: _card_rank(f, consumers)) + ranked = sorted(candidates, key=lambda f: card_rank(f, consumers)) reads = _SectionReads(kept, ranked, consumers) requiring, weak = _weak_starts(ranked, reads) chosen = _chosen_members(ranked, reads, requiring) @@ -316,7 +316,7 @@ def _start_groups( for f in ranked: for emulator, entry, system, name, named in reads.reading(f): place = _group_place(emulator, entry) - if place is not None and chosen.get(place) != (named or _visible(name)): + if place is not None and chosen.get(place) != (named or visible_name(name)): continue try: key = system_name(system) if system else None @@ -327,12 +327,12 @@ def _start_groups( named_keys = [key for key in groups if key is not None] if None in groups and named_keys: # An entry that names no system reads the section's own console. - heading = _heading_name(*section) if section else None + heading = heading_name(*section) if section else None groups[heading if heading in groups else named_keys[0]].absorb(groups.pop(None)) return groups -def _start_with( +def start_with( files: list[dict], consumers: FileConsumers, first_below: bool = True, section: tuple[str, str] | None = None, ) -> list[str]: @@ -350,7 +350,7 @@ def _start_with( return _start(files, consumers, first_below, section)[0] -def _start_order( +def start_order( files: list[dict], consumers: FileConsumers, section: tuple[str, str] | None = None, ) -> list[str]: """The sha1s of the files a section's start line names, in its order: @@ -372,7 +372,7 @@ def _start( lines = _lead_file(groups) if not lines: lines = _group_lines(groups, first_below, held, sha1s, - _section_label(*section) if section and section != OTHER_ARCADE else "") + section_label(*section) if section and section != OTHER_ARCADE else "") order: list[str] = [] for line in lines: for visible in re.findall(r"`([^`]*)`", line): @@ -438,7 +438,7 @@ def _group_lines( def _display_names(emulators: set[str] | list[str]) -> list[str]: - return sorted({_emulator_display(e) for e in emulators}, key=str.casefold) + return sorted({emulator_display(e) for e in emulators}, key=str.casefold) def _names_counted(names: list[str], most: int = 3, noun: str = "") -> str: @@ -447,7 +447,7 @@ def _names_counted(names: list[str], most: int = 3, noun: str = "") -> str: if len(names) > most + 1: more = f"{len(names) - most} more" + (f" {noun}" if noun else "") return f"{', '.join(names[:most])} and {more}" - return _said_as_list(names) + return said_as_list(names) def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]: @@ -476,7 +476,7 @@ def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]: zipped = " Keep it zipped." if top.casefold().endswith(".zip") else "" names = _display_names(readers) said = (_names_counted(names, 2, "emulators") if len(names) > 2 - else _said_as_list(names)) + else said_as_list(names)) lines = [f"**Start with** {written[top]}.{zipped} {said} read{'s' if len(names) == 1 else ''} it.", ""] # The emulators that require other files and not this one, by the @@ -491,7 +491,7 @@ def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]: for files, who in sorted(others.items(), key=lambda item: (-len(item[1]), item[0])): names = _display_names(who) verb = "reads" if len(names) == 1 else "read" - sentences.append(f"{_names_counted(names)} {verb} {_said_as_list(list(files))} instead.") + sentences.append(f"{_names_counted(names)} {verb} {said_as_list(list(files))} instead.") if sentences: lines += [" ".join(sentences), ""] return lines @@ -510,7 +510,7 @@ class _GroupWords: return ", ".join(names) # The first three by rank, the rest counted: "the 9 files" named # none, and the Neo Geo BIOS everyone reads is filed under Arcade. - return f"{', '.join(names[:3])} and {_count(len(names) - 3, 'more file')}" + ( + return f"{', '.join(names[:3])} and {count_text(len(names) - 3, 'more file')}" + ( ", first below" if below else "") def instead_of(self, line: str, names: list[str], answered: set[str]) -> str: @@ -519,16 +519,16 @@ class _GroupWords: group = self.group readers = group.line_readers.get(line, {}) others: dict[tuple[str, ...], set[str]] = {} - for emulator in sorted(set().union(*(readers.get(_visible(n), set()) for n in names)) + for emulator in sorted(set().union(*(readers.get(visible_name(n), set()) for n in names)) - answered): - theirs = tuple(group.as_read(_visible(n), {emulator}, line) for n in names - if emulator in readers.get(_visible(n), set())) + theirs = tuple(group.as_read(visible_name(n), {emulator}, line) for n in names + if emulator in readers.get(visible_name(n), set())) others.setdefault(theirs, set()).add(emulator) sentences = [] for files, who in sorted(others.items(), key=lambda item: (-len(item[1]), item[0])): shown = _display_names(who) verb = "reads" if len(shown) == 1 else "read" - sentences.append(f"{_names_counted(shown)} {verb} {_said_as_list(list(files))} instead.") + sentences.append(f"{_names_counted(shown)} {verb} {said_as_list(list(files))} instead.") return " ".join(sentences) def split(self, line: str, names: list[str]) -> tuple[list[str], str, set[str]]: @@ -538,13 +538,13 @@ class _GroupWords: for one slot: "fdsbios.zip, disksys.rom" read as two files to get.""" group = self.group readers = group.line_readers.get(line, {}) - sets = {n: readers.get(_visible(n), set()) for n in names} + sets = {n: readers.get(visible_name(n), set()) for n in names} lead = max(names, key=lambda n: len(sets[n])) main = [n for n in names if n == lead or sets[n] <= sets[lead]] rest = [n for n in names if n not in main] # A file the lead's readers require beside it is a start file too, # unless most of its readers take it as an extra. - main = [n for n in main if n == lead or (line, _visible(n)) not in group.extras] + main = [n for n in main if n == lead or (line, visible_name(n)) not in group.extras] return main, self.instead_of(line, rest, set(sets[lead])), set().union(*sets.values()) @@ -577,14 +577,14 @@ def _runs_without(words: _GroupWords) -> list[tuple[str, str]]: def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str], set[str]]: """The lines of the files picked by region, the emulators they answer and the names they give.""" - from model.region import _PARENT + from model.region import PARENT group = words.group - order = _region_order() + order = region_order() # A territory its region answers the same way adds nothing: Brazil # under Latin America. by_region = {r: names for r, names in group.by_region.items() - if group.by_region.get(_PARENT.get(r, "")) != names} + if group.by_region.get(PARENT.get(r, "")) != names} # Regions that need the same files share a line. regional: dict[tuple[str, ...], str] = {} answered: set[str] = set() @@ -592,7 +592,7 @@ def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str], for region in sorted(by_region, key=lambda r: (order.get(r, len(order)), r)): main, sentence, readers = words.split(region, by_region[region]) answered |= readers - shown |= {_visible(n) for n in by_region[region]} + shown |= {visible_name(n) for n in by_region[region]} text = f"{words.listed(main)}. {sentence}" if sentence else words.listed(main) same = next((rs for rs, held in regional.items() if held == text), None) if same is None: @@ -600,7 +600,7 @@ def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str], else: regional[same + (region,)] = regional.pop(same) - out = [(", ".join(_region_words(r) for r in regions), regional[regions]) + out = [(", ".join(region_words(r) for r in regions), regional[regions]) for regions in sorted(regional, key=lambda rs: (order.get(rs[0], len(order)), rs))] return out, answered, shown @@ -613,10 +613,10 @@ def _plain_lines(words: _GroupWords, regional: bool, answered: set[str], # A name a region line gives already is no "also", and one only # emulators no region line answers reads is an "instead": armsx1 reads # scph1001.bin where the others pick a BIOS by region. - plain = [n for n in group.plain if _visible(n) not in shown] + plain = [n for n in group.plain if visible_name(n) not in shown] if plain and regional: readers = group.line_readers.get("", {}) - also = [n for n in plain if readers.get(_visible(n), set()) & answered] + also = [n for n in plain if readers.get(visible_name(n), set()) & answered] if also: out.append(("", words.listed(also))) sentence = words.instead_of("", [n for n in plain if n not in also], answered) @@ -646,12 +646,12 @@ def _group_start(group: _StartGroup, first_below: bool) -> list[tuple[str, str]] out, answered, shown = _region_lines(words) out.extend(_plain_lines(words, bool(out), answered, shown)) if not out and group.optional: - out.append(("*", f"{_without_files(group.emulators)}. " + out.append(("*", f"{without_files(group.emulators)}. " f"For full accuracy: {words.listed(group.optional)}.")) elif not out and group.extra: # The Mega Drive's emulators read the TMSS BIOS when it is there: # the section said nothing under a home page saying none is needed. - out.append(("*", f"{_without_files(group.emulators)}. " + out.append(("*", f"{without_files(group.emulators)}. " f"Optional: {words.listed(group.extra, False)}.")) return out @@ -680,7 +680,7 @@ def _start_lines(block: list[tuple[str, str]], console: str = "") -> list[str]: return [*lines, ""] -def _cards_markdown(cards: list[Card]) -> list[str]: +def cards_markdown(cards: list[Card]) -> list[str]: """Primaries, then the variants in a closed block.""" lines = [line for variant, card, _sha1 in cards if not variant for line in card] variants = [card for variant, card, _sha1 in cards if variant] @@ -693,10 +693,10 @@ def _cards_markdown(cards: list[Card]) -> list[str]: return lines -def _parts(cards: list[_Item], budget: int, sizes: list[int]) -> list[list[_Item]]: +def card_runs(cards: list[Item], budget: int, sizes: list[int]) -> list[list[Item]]: """Cards in runs of at most ``budget`` bytes, in order, ``sizes`` giving each card's weight.""" - parts: list[list[_Item]] = [[]] + parts: list[list[Item]] = [[]] size = 0 for index, card in enumerate(cards): weight = sizes[index] @@ -708,7 +708,7 @@ def _parts(cards: list[_Item], budget: int, sizes: list[int]) -> list[list[_Item return parts -def _console_heading(manufacturer: str, console: str, label: str = "") -> str: +def console_heading(manufacturer: str, console: str, label: str = "") -> str: """A console's heading, its name alone. An icon on 79 of 544 headings read as missing art on the rest, set the text at two positions on one page and faded out on one theme or the other. ``label`` is the text @@ -716,10 +716,10 @@ def _console_heading(manufacturer: str, console: str, label: str = "") -> str: return f"## {label or console} {{ #{console_anchor(manufacturer, console)} }}" -def _romset_note(consoles: dict[str, list]) -> list[str]: +def romset_note(consoles: dict[str, list]) -> list[str]: """The line a page of MAME or FBNeo sets carries: an arcade player looking for the version found the answer only under Reference.""" - releases = _romset_releases() + releases = romset_releases() if not any(str(f.get("name", "")) in releases for files in consoles.values() for f in files): return [] return ["MAME and FBNeo sets must match the emulator's version. " @@ -732,7 +732,7 @@ OTHER_ARCADE = ("Arcade", "Arcade") OTHER_ARCADE_LABEL = "Other arcade files" -def _section_label(manufacturer: str, console: str) -> str: +def section_label(manufacturer: str, console: str) -> str: """The heading a section shows.""" if (manufacturer, console) == OTHER_ARCADE: return OTHER_ARCADE_LABEL diff --git a/scripts/sitegen/steps.py b/scripts/sitegen/steps.py index a40465860..cb6a05948 100644 --- a/scripts/sitegen/steps.py +++ b/scripts/sitegen/steps.py @@ -30,12 +30,12 @@ from sitegen.diagrams import ( STROKE, TEXT_SIZE, WIDE, - _badge, - _badge_side, - _line, - _n, - _rect, - _text, + badge, + badge_side, + svg_connector, + svg_number, + svg_rect, + svg_text, diagram_files, pictures, svg_document, @@ -105,7 +105,7 @@ def description(tab: str) -> str: def _stroke(d: str, cls: str = "rb-d-line", width: float = 1.5) -> str: - return f'' + return f'' def _key_width(label: str) -> float: @@ -120,9 +120,9 @@ def _keys(x: float, y: float, w: float, word: str) -> list[str]: top = y + ICON_H / 2 - 12 for label in labels: width = _key_width(label) - out.append(_rect(left, top, width, 24, accent=True)) + out.append(svg_rect(left, top, width, 24, accent=True)) out.append( - f'{escape(label)}') left += width + 4 return out @@ -130,8 +130,8 @@ def _keys(x: float, y: float, w: float, word: str) -> list[str]: def _menu(x: float, y: float, w: float) -> list[str]: cx, top = x + w / 2, y + 4 - out = [_rect(cx - 22, top, 44, 36)] - out += [_stroke(f"M{_n(cx - 14)} {_n(top + 10 + 8 * i)} H{_n(cx + 14)}") for i in range(3)] + out = [svg_rect(cx - 22, top, 44, 36)] + out += [_stroke(f"M{svg_number(cx - 14)} {svg_number(top + 10 + 8 * i)} H{svg_number(cx + 14)}") for i in range(3)] return out @@ -139,11 +139,11 @@ def _search(x: float, y: float, w: float, word: str) -> list[str]: width = min(w - 4, len(word) * KEY_SIZE * 0.62 + 34) left, top = x + (w - width) / 2, y + ICON_H / 2 - 12 return [ - _rect(left, top, width, 24, accent=True), - f'', - _stroke(f"M{_n(left + 15)} {_n(top + 15)} L{_n(left + 19)} {_n(top + 19)}"), - f'{escape(word)}', ] @@ -151,36 +151,36 @@ def _search(x: float, y: float, w: float, word: str) -> list[str]: def _window(x: float, y: float, w: float) -> list[str]: cx, top = x + w / 2, y + 2 return [ - _rect(cx - 32, top, 64, 40), - _stroke(f"M{_n(cx - 32)} {_n(top + 9)} H{_n(cx + 32)}"), - f'>_', ] def _copy(x: float, y: float, w: float) -> list[str]: cx, top = x + w / 2, y + 6 - return [_rect(cx - 12, top, 18, 24), _rect(cx - 6, top + 7, 18, 24, accent=True)] + return [svg_rect(cx - 12, top, 18, 24), svg_rect(cx - 6, top + 7, 18, 24, accent=True)] def _mouse(x: float, y: float, w: float) -> list[str]: cx, top = x + w / 2, y + 2 return [ - f'', # The right button, the one to press. - f'', - _stroke(f"M{_n(cx)} {_n(top)} V{_n(top + 14)} M{_n(cx - 13)} {_n(top + 14)} " - f"H{_n(cx + 13)}"), + f'', + _stroke(f"M{svg_number(cx)} {svg_number(top)} V{svg_number(top + 14)} M{svg_number(cx - 13)} {svg_number(top + 14)} " + f"H{svg_number(cx + 13)}"), ] def _power(x: float, y: float, w: float) -> list[str]: cx, cy = x + w / 2, y + ICON_H / 2 + 2 return [ - _stroke(f"M{_n(cx - 9)} {_n(cy - 11)} A14 14 0 1 0 {_n(cx + 9)} {_n(cy - 11)}", width=2.5), - _stroke(f"M{_n(cx)} {_n(cy - 18)} V{_n(cy - 2)}", width=2.5), + _stroke(f"M{svg_number(cx - 9)} {svg_number(cy - 11)} A14 14 0 1 0 {svg_number(cx + 9)} {svg_number(cy - 11)}", width=2.5), + _stroke(f"M{svg_number(cx)} {svg_number(cy - 18)} V{svg_number(cy - 2)}", width=2.5), ] @@ -202,34 +202,34 @@ def _wide(steps: tuple[Step, ...]) -> tuple[float, float, list[str]]: out: list[str] = [] for index, (step, lines) in enumerate(zip(steps, captions)): x = 1 + index * (width + gap) - out.append(_rect(x, 1, width, height)) - out += _badge(x + 8, 8, str(index + 1)) + out.append(svg_rect(x, 1, width, height)) + out += badge(x + 8, 8, str(index + 1)) out += _icon(step, x + 4, 30, width - 8) y = 30 + ICON_H + 24 for line in lines: - out.append(_text(x + width / 2, y, line, anchor="middle")) + out.append(svg_text(x + width / 2, y, line, anchor="middle")) y += 18 if index < len(steps) - 1: mid = 1 + height / 2 - out += _line([(x + width + 1, mid), (x + width + gap - 1, mid)]) + out += svg_connector([(x + width + 1, mid), (x + width + gap - 1, mid)]) return WIDE, height + 2, out def _narrow(steps: tuple[Step, ...]) -> tuple[float, float, list[str]]: """One card a row: number, pictogram, caption.""" icon_w, row_gap = 112.0, 8.0 - text_x = 8 + _badge_side("9") + 6 + icon_w + 8 + text_x = 8 + badge_side("9") + 6 + icon_w + 8 out: list[str] = [] y = 1.0 for index, step in enumerate(steps): lines = wrap(step.caption, NARROW - text_x - 8, TEXT_SIZE) height = max(ICON_H + 12, len(lines) * 18 + 16) - out.append(_rect(1, y, NARROW - 2, height)) - out += _badge(8, y + height / 2 - 10, str(index + 1)) - out += _icon(step, 8 + _badge_side("9") + 6, y + (height - ICON_H) / 2, icon_w) + out.append(svg_rect(1, y, NARROW - 2, height)) + out += badge(8, y + height / 2 - 10, str(index + 1)) + out += _icon(step, 8 + badge_side("9") + 6, y + (height - ICON_H) / 2, icon_w) ty = y + height / 2 - (len(lines) - 1) * 9 + 5 for line in lines: - out.append(_text(text_x, ty, line)) + out.append(svg_text(text_x, ty, line)) ty += 18 y += height + row_gap return NARROW, y - row_gap + 1, out diff --git a/scripts/sitegen/structured.py b/scripts/sitegen/structured.py index 082b385b2..7e3c998ec 100644 --- a/scripts/sitegen/structured.py +++ b/scripts/sitegen/structured.py @@ -11,12 +11,13 @@ from model.collection import collection_paths from model.systemnames import system_name from sitegen import starlight as sitestarlight from sitegen.cards import emulator_file_anchors -from sitegen.config import REPO_URL, SITE_NAME, SITE_URL, _REPO_ROOT +from sitegen.config import REPO_URL, SITE_NAME, SITE_URL +from core.paths import REPO_ROOT from sitegen.descriptions import EMULATOR_SNIPPETS, NOTHING_TO_FETCH, PAGE_DATA -from sitegen.emulatorcards import _snippet_noun +from sitegen.emulatorcards import snippet_noun from sitegen.install import comes_with_app -from sitegen.lookup import _data_member_digests, _hash_values -from sitegen.render import _system_page_map +from sitegen.lookup import data_member_digests, sorted_hash_values +from sitegen.render import system_page_map from sitegen.write import write_if_changed @@ -50,12 +51,12 @@ def collection_dat(db: dict, generated_at: str) -> str: games, generated_at) -def _write_platform_dats(folder: Path, db: dict, members: dict, generated_at: str) -> list[Path]: +def write_platform_dats(folder: Path, db: dict, members: dict, generated_at: str) -> list[Path]: """downloads/dat/.dat for each install manifest.""" folder.mkdir(parents=True, exist_ok=True) - digests = _data_member_digests(members) + digests = data_member_digests(members) written = [] - for source in sorted((_REPO_ROOT / "install").glob("*.json")): + for source in sorted((REPO_ROOT / "install").glob("*.json")): manifest = json.loads(source.read_text(encoding="utf-8")) path = folder / f"{source.stem}.dat" write_if_changed(str(path), platform_dat(manifest, db, digests, generated_at)) @@ -197,7 +198,7 @@ def platform_structured_data(name: str, coverage: dict) -> dict: identifiers = [ f"{field}:{value}" for field in ("sha1", "md5", "crc32", "sha256") - for value in _hash_values(entry.get(field)) + for value in sorted_hash_values(entry.get(field)) ] if identifiers: part["identifier"] = identifiers @@ -302,7 +303,7 @@ def record_emulator_page(name: str, profile: dict) -> None: fetched = [f for f in listed if f.get("name") and not comes_with_app(f)] systems = profile.get("systems") or [] first = systems[0] if systems else "" - makers = [_system_page_map[sys_id][0] for sys_id in systems if sys_id in _system_page_map] + makers = [system_page_map[sys_id][0] for sys_id in systems if sys_id in system_page_map] if makers: sitestarlight.EMULATOR_CARDS[f"emulators/{name}"] = makers[0] else: @@ -320,7 +321,7 @@ def record_emulator_page(name: str, profile: dict) -> None: system_name(first) if 0 < len(systems) <= 5 else "", list(names.values()), len({Path(str(f["name"])).name.casefold() for f in fetched if f.get("required") is True}), - _snippet_noun(names.values(), len(firmware), len(fetched)), + snippet_noun(names.values(), len(firmware), len(fetched)), ) if listed and all(comes_with_app(f) for f in listed): NOTHING_TO_FETCH.add(key) @@ -370,7 +371,7 @@ def emulator_structured_data(profile: dict) -> dict: identifiers = [ f"{field}:{value}" for field in ("sha1", "sha256", "md5", "crc32") - for value in _hash_values(f.get(field)) + for value in sorted_hash_values(f.get(field)) ] part: dict[str, object] = { "@type": "CreativeWork", @@ -389,7 +390,7 @@ def emulator_structured_data(profile: dict) -> dict: "identifier": [ f"{field}:{value}" for field in ("sha1", "crc32") - for value in _hash_values(member.get(field)) + for value in sorted_hash_values(member.get(field)) ], } for member in f.get("contents") or [] diff --git a/scripts/sitegen/systempages.py b/scripts/sitegen/systempages.py index 55341b0b0..7802a5f80 100644 --- a/scripts/sitegen/systempages.py +++ b/scripts/sitegen/systempages.py @@ -10,12 +10,13 @@ import re import urllib.parse from dataclasses import dataclass -from model.collection import SECTION_LABELS, _slug +from model.collection import SECTION_LABELS, manufacturer_slug from model.composition import GAME_DATA_TOPS from packs.crossref import FileConsumers from sitegen import markup -from sitegen.cards import _icon_symbol -from sitegen.config import _REPO_ROOT, _date_line +from sitegen.cards import icon_symbol +from sitegen.config import date_line +from core.paths import REPO_ROOT from sitegen.consolecards import ( CARD_HTML_RATIO, CONSOLE_PAGES, @@ -23,26 +24,26 @@ from sitegen.consolecards import ( INSTALL_HTML_RATIO, SYSTEM_PAGE_BUDGET, SYSTEM_SUMMARY_HTML, - _console_cards, - _install_box_weight, + console_cards, + install_box_weight, ) from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT from sitegen.fields import search_excluded -from sitegen.home import _next_block -from sitegen.install import _console_install_block, _platform_display -from sitegen.parts import _parent_front_matter -from sitegen.render import _count, _slugify_anchor, console_href, record_console_pages +from sitegen.home import next_block +from sitegen.install import console_install_block, platform_display +from sitegen.parts import parent_front_matter +from sitegen.render import count_text, slugify_anchor, console_href, record_console_pages from sitegen.startwith import ( OTHER_ARCADE, - _cards_markdown, - _console_heading, - _parts, - _romset_note, - _section_label, - _start_order, - _start_with, + cards_markdown, + console_heading, + card_runs, + romset_note, + section_label, + start_order, + start_with, ) -from sitegen.systemsindex import _folder_emulator +from sitegen.systemsindex import folder_emulator _NEXT_FROM_SYSTEMS = [ @@ -227,7 +228,7 @@ def _system_front_matter( """The front matter of a system page: the page it belongs to, the parts before and after it (label, site path), its search weight and the consoles it holds, which the search reads as a field.""" - lines = _parent_front_matter(parent) + lines = parent_front_matter(parent) for key, link in (("prev", prev), ("next", following)): if link: lines += [f"{key}:", f" label: {json.dumps(link[0])}", f" link: {json.dumps(link[1])}"] @@ -247,7 +248,7 @@ def _part_weight() -> float: def _manifest_systems(platform: str) -> frozenset[str]: """The system ids a platform's install manifest records: --system refuses any other.""" - manifest = _REPO_ROOT / "install" / f"{platform}.json" + manifest = REPO_ROOT / "install" / f"{platform}.json" if not manifest.is_file(): return frozenset() document = json.loads(manifest.read_text(encoding="utf-8")) @@ -274,7 +275,7 @@ def _install_pairs( if recorded: pairs.append((platform, recorded[0])) have.add(platform) - return sorted(pairs, key=lambda pair: (_platform_display(pair[0]).casefold(), pair[1])) + return sorted(pairs, key=lambda pair: (platform_display(pair[0]).casefold(), pair[1])) @dataclass(frozen=True) @@ -313,7 +314,7 @@ class _MakerPages: def __post_init__(self) -> None: manufacturer, consoles = self.manufacturer, self.consoles - self.slug = _slug(manufacturer) + self.slug = manufacturer_slug(manufacturer) self.boards = {console: _BOARD_CONSOLES[console] for console in consoles if manufacturer == "Arcade" and console in _BOARD_CONSOLES} self.json_next = (f"[Every hash of these files, as JSON](../api/v1/systems/" @@ -324,7 +325,7 @@ class _MakerPages: boards = self.boards self.ordered = sorted(consoles, key=lambda c: (bool(boards) and c not in boards, c)) self.starts = {console: [] if boards and console not in boards - else _start_order(consoles[console], self.consumers, (manufacturer, console)) + else start_order(consoles[console], self.consumers, (manufacturer, console)) for console in consoles} # One line, then the legend closed: four paragraphs said the same on # every maker's page before its first console. @@ -350,18 +351,18 @@ class _MakerPages: def start_of(self, console: str, first_below: bool = True) -> list[str]: if self.boards and console not in self.boards: return [] - return [*_start_with(self.consoles[console], self.consumers, first_below, + return [*start_with(self.consoles[console], self.consumers, first_below, (self.manufacturer, console)), *_boards_line(self.manufacturer, console)] def cards_of(self, console: str, anchors: set[str], by_name: bool = False) -> list[Card]: - return _console_cards(self.manufacturer, self.consoles[console], self.consumers, anchors, + return console_cards(self.manufacturer, self.consoles[console], self.consumers, anchors, by_name, self.starts[console]) def install_block(self, console: str) -> list[str]: lead = self.starts[console][0] if self.starts[console] else None - return _console_install_block( - _section_label(self.manufacturer, console), + return console_install_block( + section_label(self.manufacturer, console), _install_pairs(self.installs.get(console, []), lead, self.consumers)) def all_sections(self) -> dict[str, list[Card]]: @@ -370,28 +371,28 @@ class _MakerPages: def consoles_front(self, kept: set[str] | None = None) -> list[str]: return _system_front_matter(consoles=[ - _section_label(self.manufacturer, c) for c in self.machines + section_label(self.manufacturer, c) for c in self.machines if kept is None or c in kept]) def head(self, front: list[str]) -> list[str]: """A maker's page down to its first console.""" return [ *front, f"# {self.manufacturer}", "", self.intro, "", *self.legend, - *_romset_note(self.consoles), *_icon_symbol(), + *romset_note(self.consoles), *icon_symbol(), ] def whole_page(self, sections: dict[str, list[Card]]) -> str: lines = self.head(self.front) for console, cards in sections.items(): - lines.append(_console_heading(self.manufacturer, console, - _section_label(self.manufacturer, console))) + lines.append(console_heading(self.manufacturer, console, + section_label(self.manufacturer, console))) lines.append("") lines.extend(self.start_of(console)) lines.extend(self.install_block(console)) - lines.extend(_cards_markdown(cards)) + lines.extend(cards_markdown(cards)) lines.append("") - lines.extend(_next_block([*_NEXT_FROM_SYSTEMS, self.json_next])) - lines.extend(["", _date_line()]) + lines.extend(next_block([*_NEXT_FROM_SYSTEMS, self.json_next])) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" def cut(self, console: str, by_name: bool) -> list[list[Card]]: @@ -402,16 +403,16 @@ class _MakerPages: with markup.using("mkdocs"): sizes = [_card_weight(card) for _variant, card, _sha1 in self.cards_of( console, set(), by_name)] - parts = _parts(cards, self.budget, sizes) + parts = card_runs(cards, self.budget, sizes) if len(parts) < 2: return parts # Even parts: cut at budget, the PlayStation 2 was 137 cards # and 4. The same number of parts, each near the mean. share = -(-sum(sizes) // len(parts)) - even = _parts(cards, share, sizes) + even = card_runs(cards, share, sizes) while len(even) > len(parts): share += max(1, share // 50) - even = _parts(cards, share, sizes) + even = card_runs(cards, share, sizes) return even def moved(self, weights: dict[str, int], rendered: dict[str, float]) -> set[str]: @@ -445,7 +446,7 @@ class _MakerPages: weight=_part_weight() if len(stems) > 1 else None, consoles=[label] if index == 0 and console in self.machines else None), # The crumbs end on the maker's page: no line says it again. - f"# {plan.titles[index]}", "", *_icon_symbol(), + f"# {plan.titles[index]}", "", *icon_symbol(), ] if len(stems) > 1: others = ", ".join( @@ -458,14 +459,14 @@ class _MakerPages: if index == 0: lines.extend(self.start_of(console, len(stems) == 1)) lines.extend(self.legend) - lines.extend(_romset_note({console: self.consoles[console]})) + lines.extend(romset_note({console: self.consoles[console]})) lines.extend(self.install_block(console)) lines.extend(["## Files", ""]) - lines.extend(_cards_markdown(part)) + lines.extend(cards_markdown(part)) lines.append("") - lines.extend(_next_block([f"[{self.manufacturer}]({self.slug}.md), every section"] + lines.extend(next_block([f"[{self.manufacturer}]({self.slug}.md), every section"] + _NEXT_FROM_SYSTEMS + [self.json_next])) - lines.extend(["", _date_line()]) + lines.extend(["", date_line()]) return "\n".join(lines) + "\n" def moved_section(self, console: str, pages: dict[str, tuple[str, dict[str, list]]]) -> list[str]: @@ -474,7 +475,7 @@ class _MakerPages: from sitegen.render import board_slug manufacturer = self.manufacturer - label = _section_label(manufacturer, console) + label = section_label(manufacturer, console) # One page keeps the required files first. Parts are named by their # first and last file, so a console cut in parts goes by name, the # files the start line names first. @@ -483,7 +484,7 @@ class _MakerPages: parts = self.cut(console, True) board = self.boards.get(console) base = (f"arcade-{board_slug(board)}" if board - else f"{self.slug}-{_slugify_anchor(console) or 'files'}") + else f"{self.slug}-{slugify_anchor(console) or 'files'}") stems = [base if index == 0 else f"{base}-{index + 1}" for index in range(len(parts))] clash = set(stems) & set(pages) if clash: @@ -495,12 +496,12 @@ class _MakerPages: # A part by the files it holds: "Arcade: Arcade, part 3 of 5" said # nothing a search result could use. A folder under Other goes by # its emulator's name: "mame files" named the folder. - named = _folder_emulator(console)[0] if manufacturer == "Other" else None + named = folder_emulator(console)[0] if manufacturer == "Other" else None titles = ([f"{manufacturer}: {named or label}"] if len(stems) == 1 else [ "{} files {} to {}".format(named or _part_name(manufacturer, console), *_part_ends(part, lead)) for part in parts]) - count = _count(len(self.consoles[console]), "file") + count = count_text(len(self.consoles[console]), "file") summary = list(self.start_of(console, False)) if len(stems) == 1: own = "its" if len(self.consoles[console]) == 1 else "their" @@ -555,7 +556,7 @@ def system_pages( # page, which the card weights never counted. A page is also cut when # its estimate as it renders passes the summary's. with markup.using("mkdocs"): - boxes = {console: _install_box_weight(maker.install_block(console)) for console in consoles} + boxes = {console: install_box_weight(maker.install_block(console)) for console in consoles} rendered = {console: CARD_HTML_RATIO * weights[console] + INSTALL_HTML_RATIO * boxes[console] for console in weights} if (not maker.boards and manufacturer not in CONSOLE_PAGES and len(measured_text) <= budget @@ -568,18 +569,18 @@ def system_pages( summary = maker.head(maker.consoles_front(set(consoles) - moved)) summary_anchors: set[str] = set() for console in maker.ordered: - label = _section_label(manufacturer, console) - summary.append(_console_heading(manufacturer, console, label)) + label = section_label(manufacturer, console) + summary.append(console_heading(manufacturer, console, label)) summary.append("") if console not in moved: summary.extend(maker.start_of(console)) summary.extend(maker.install_block(console)) - summary.extend(_cards_markdown(maker.cards_of(console, summary_anchors))) + summary.extend(cards_markdown(maker.cards_of(console, summary_anchors))) summary.append("") continue summary.extend(maker.moved_section(console, pages)) - summary.extend(_next_block([*_NEXT_FROM_SYSTEMS, maker.json_next])) - summary.extend(["", _date_line()]) + summary.extend(next_block([*_NEXT_FROM_SYSTEMS, maker.json_next])) + summary.extend(["", date_line()]) kept = {console: files for console, files in consoles.items() if console not in moved} return {slug: ("\n".join(summary) + "\n", kept), **pages} @@ -604,7 +605,7 @@ def _part_range(part: list[Card], lead: set[str] | frozenset[str] = frozenset()) first, last = _part_ends(part, lead) if len(part) == 1: return f"`{first}`" - return f"{_count(len(part), 'file')}, `{first}` to `{last}`" + return f"{count_text(len(part), 'file')}, `{first}` to `{last}`" def generate_system_page( @@ -619,4 +620,4 @@ def generate_system_page( install command the section offers. A page over the budget is the summary system_pages writes, its consoles on pages of their own. """ - return system_pages(manufacturer, consoles, consumers, installs)[_slug(manufacturer)][0] + return system_pages(manufacturer, consoles, consumers, installs)[manufacturer_slug(manufacturer)][0] diff --git a/scripts/sitegen/systemsindex.py b/scripts/sitegen/systemsindex.py index 769717946..823426678 100644 --- a/scripts/sitegen/systemsindex.py +++ b/scripts/sitegen/systemsindex.py @@ -2,21 +2,21 @@ from __future__ import annotations -from model.collection import SECTION_LABELS, _profiles_on_disk, _slug +from model.collection import SECTION_LABELS, profiles_on_disk, manufacturer_slug from model.composition import GAME_DATA_TOPS from sitegen import starlight as sitestarlight -from sitegen.render import _count, console_href -from sitegen.startwith import _section_label +from sitegen.render import count_text, console_href +from sitegen.startwith import section_label def _console_display(manufacturer: str, console: str) -> str: """A console section's name as the reader looks for it: the heading system_name gives its id, or the folder alone under a program's top (Other, Arcade), where "Other mame" would name nothing.""" - from model.collection import _PROGRAM_TOPS - from model.systemnames import _heading_name + from model.collection import PROGRAM_TOPS + from model.systemnames import heading_name - return console if manufacturer in _PROGRAM_TOPS else _heading_name(manufacturer, console) + return console if manufacturer in PROGRAM_TOPS else heading_name(manufacturer, console) def generate_systems_index(manufacturers: dict) -> str: @@ -42,8 +42,8 @@ def generate_systems_index(manufacturers: dict) -> str: "Every BIOS file the collection holds, by console. Open a console to " "see each file, the emulators that read it and the setups that list it.", "", - f"{_count(total_consoles, 'console')}, {_count(total_files, 'file')} in the " - f"repository, from {_count(total_mfr, 'manufacturer')}.", + f"{count_text(total_consoles, 'console')}, {count_text(total_files, 'file')} in the " + f"repository, from {count_text(total_mfr, 'manufacturer')}.", "", ] @@ -68,8 +68,8 @@ def generate_systems_index(manufacturers: dict) -> str: "as the data of a game, rather than the BIOS of a machine."), ): rows = sorted( - ((_folder_emulator(console)[0] if group == "programs" - else _section_label(mfr, console) if mfr == "Arcade" + ((folder_emulator(console)[0] if group == "programs" + else section_label(mfr, console) if mfr == "Arcade" or (mfr, console) in SECTION_LABELS else _console_display(mfr, console), mfr, console, len(files)) for mfr, consoles in manufacturers.items() if kind(mfr) == group @@ -87,11 +87,11 @@ def generate_systems_index(manufacturers: dict) -> str: # every maker cell said Other. lines += ["| Emulator | Files |", "|---------|------:|"] for name, mfr, console, count in rows: - href = console_href(_slug(mfr), console).removeprefix("systems/") - key = _folder_emulator(console)[1] + href = console_href(manufacturer_slug(mfr), console).removeprefix("systems/") + key = folder_emulator(console)[1] cell = name.replace("|", "-") cell = f"[{cell}](../emulators/{key}.md)" if key else cell - lines.append(f"| {cell} | [{_count(count, 'file')}]({href}) |") + lines.append(f"| {cell} | [{count_text(count, 'file')}]({href}) |") lines.append("") continue lines += [ @@ -102,18 +102,18 @@ def generate_systems_index(manufacturers: dict) -> str: ] for name, mfr, console, count in rows: cell = name.replace("|", "-") - href = console_href(_slug(mfr), console).removeprefix("systems/") - lines.append(f"| [{cell}]({href}) | {count:,} | [{mfr}]({_slug(mfr)}.md) |") + href = console_href(manufacturer_slug(mfr), console).removeprefix("systems/") + lines.append(f"| [{cell}]({href}) | {count:,} | [{mfr}]({manufacturer_slug(mfr)}.md) |") lines.append("") return "\n".join(lines) + "\n" -def _folder_emulator(folder: str) -> tuple[str, str]: +def folder_emulator(folder: str) -> tuple[str, str]: """The display name and profile of the emulator a folder under Other is named after, by its profile key or its name, else the folder and "". """ - profiles = _profiles_on_disk() + profiles = profiles_on_disk() if folder in profiles and profiles[folder].get("type") != "alias" and profiles[folder].get("role") != "test": return str(profiles[folder].get("emulator") or folder), folder for key in sorted(profiles): diff --git a/scripts/sitegen/versions.py b/scripts/sitegen/versions.py index 928106b1e..b3c04c226 100644 --- a/scripts/sitegen/versions.py +++ b/scripts/sitegen/versions.py @@ -10,7 +10,7 @@ from model import siteinputs from model.composition import count_catalog_matched from model.platforms import load_platform_config from model.profiles import unique_emulator_profiles -from sitegen.config import RELEASE_URL, REPO_URL, _timestamp +from sitegen.config import RELEASE_URL, REPO_URL, data_timestamp def compute_stats(db: dict, coverages: dict, profiles: dict) -> dict: @@ -20,7 +20,7 @@ def compute_stats(db: dict, coverages: dict, profiles: dict) -> dict: systems.update(p.get("systems", [])) return { "schema_version": 1, - "generated_at": _timestamp(), + "generated_at": data_timestamp(), "files": db.get("total_files", 0), "size_bytes": db.get("total_size", 0), "platforms": len(coverages), diff --git a/scripts/sitegen/wanted.py b/scripts/sitegen/wanted.py index b12a6188f..a515f946d 100644 --- a/scripts/sitegen/wanted.py +++ b/scripts/sitegen/wanted.py @@ -24,7 +24,7 @@ from pathlib import Path from romrecipes import ledger as romrecipes_ledger from resolve.layout import runs_standalone from model.profiles import unique_emulator_profiles -from packs.crossref import _first_hash +from packs.crossref import first_hash from core.hashing import cut_md5_owner, parse_hash_list from resolve.review import LARGE_FILE_ISSUE_URL, Placement, placement from resolve.validation import deliverable, filter_files_by_mode, installed_with_emulator @@ -125,7 +125,7 @@ def gap_entries(profile: dict, name: str, identity: str, unsourceable: bool) -> if unsourceable: return [f for f in named if f.get("unsourceable")] or named if identity: - return [f for f in named if _first_hash(f) == identity] or named + return [f for f in named if first_hash(f) == identity] or named return named diff --git a/scripts/sitegen/whichpack.py b/scripts/sitegen/whichpack.py index 8c0198549..0ea4f9211 100644 --- a/scripts/sitegen/whichpack.py +++ b/scripts/sitegen/whichpack.py @@ -23,16 +23,16 @@ from sitegen import markup, steps as sitesteps from sitegen.config import RELEASE_URL from sitegen.guidepage import NO_ZIP_FAQ, devices_meta, first_screen_words, get_page_link from sitegen.guides import fence, terminal_tabs, trust_box -from sitegen.home import _group_keys, _next_block, _runs_on, setup_picker -from sitegen.install import _installer, has_release_pack +from sitegen.home import group_keys, next_block, runs_on_text, setup_picker +from sitegen.install import installer_module, has_release_pack from sitegen.readme import NO_PACK, download_links -from sitegen.render import _fmt_size +from sitegen.render import fmt_size # Build cross-reference indexes -def _build_file_consumers(db: dict, coverages: dict, profiles: dict) -> FileConsumers: +def build_file_consumers(db: dict, coverages: dict, profiles: dict) -> FileConsumers: """Which platforms and emulators read each collected file.""" consumers = FileConsumers(db, build_zip_contents_index(db)) consumers.add_platforms({name: cov["config"] for name, cov in coverages.items()}) @@ -41,19 +41,19 @@ def _build_file_consumers(db: dict, coverages: dict, profiles: dict) -> FileCons return consumers -def _build_emulator_file_index(profiles: dict) -> dict[str, dict]: +def build_emulator_file_index(profiles: dict) -> dict[str, dict]: """Map emulator_name -> {systems, norm}, for the platform pages. - norm holds the systems as _norm_system_id reads them: a platform files + norm holds the systems as norm_system_id reads them: a platform files the Mega Drive as sega-mega-drive and genesis_plus_gx as sega-megadrive, and an exact match left the RetroArch page with no emulator for it. """ - from model.systems import _norm_system_id + from model.systems import norm_system_id return { name: { "systems": set(profile.get("systems", [])), - "norm": {_norm_system_id(str(s)) for s in profile.get("systems", [])}, + "norm": {norm_system_id(str(s)) for s in profile.get("systems", [])}, # Archive members are read inside their archive, never by name. "names": { str(entry["name"]).lower() @@ -86,7 +86,7 @@ def _pack_cell(name: str, record: dict, prefix: str = "") -> str: link = download_links(name, record, "ZIP", page=get_page_link(name, prefix), button=lambda text, url: markup.button(text, url)) size = pack.get("download_size") if pack else None - return f"{link} ({_fmt_size(size)})" if size else link + return f"{link} ({fmt_size(size)})" if size else link def _own_root_folders(registry: dict) -> dict[str, str]: @@ -113,7 +113,7 @@ def _folder_row(key: str, display: dict[str, str], registry: dict, record: dict, folder = (f"Unzip into `{own_root[key]}`" if key in own_root and zipped else _folder_cell(key, guide)) return (f"| [{display[key]}](platforms/{key}.md) | " - f"{guide.runs_on or _runs_on(registry[key], guide)} | {folder} | " + f"{guide.runs_on or runs_on_text(registry[key], guide)} | {folder} | " f"{_pack_cell(key, record)} |") @@ -126,7 +126,7 @@ def _folder_tables(registry: dict, record: dict, display: dict[str, str]) -> lis lines: list[str] = [] alone: list[str] = [] for group, (label, _description) in DEVICE_GROUPS.items(): - members = _group_keys(registry, group, display) + members = group_keys(registry, group, display) if len(members) == 1 and not ALSO_RUNS.get(group): alone += members continue @@ -247,7 +247,7 @@ def generate_which_pack() -> str: "## Only some consoles?", "", "Pick them here, and get the files and the command. Or use the command's " - f"**{_installer().TUI_SYSTEMS_ROW}**.", + f"**{installer_module().TUI_SYSTEMS_ROW}**.", "", "", "", @@ -294,7 +294,7 @@ def generate_which_pack() -> str: ]), "Details: [All installer options](wiki/installer.md).", "", - *_next_block([ + *next_block([ "[First install, step by step](wiki/first-install.md)", "[When a game does not start](wiki/troubleshooting.md)", ]), diff --git a/scripts/sitegen/write.py b/scripts/sitegen/write.py index 95b4baf08..ba8b0a81d 100644 --- a/scripts/sitegen/write.py +++ b/scripts/sitegen/write.py @@ -17,14 +17,14 @@ import os # and a page is only removed once nothing produced it. _produced: set[str] = set() -def _record(path: str | Path) -> None: +def record_written(path: str | Path) -> None: _produced.add(os.path.realpath(str(path))) # The reader level label the decoration pass puts above a page's title. LEVEL_LABEL_START = ' bool: normalizing there too would make its own write look like a no-op and every page would lose its front matter. """ - _record(path) - return _write_artifact(path, content, normalize=_undecorated) + record_written(path) + return _write_artifact(path, content, normalize=undecorated) def write_decorated(path: str | Path, content: str) -> bool: """Write the wrapped page, comparing front matter and body together.""" - _record(path) + record_written(path) return _write_artifact(str(path), content) # A page body is written as .md and the decoration pass, which runs after @@ -69,7 +69,7 @@ def _was_produced(path: Path) -> bool: for suffix in _PAGE_SUFFIXES if suffix != path.suffix) -def _sweep_generated(docs: Path, directories: list[str]) -> int: +def sweep_generated(docs: Path, directories: list[str]) -> int: """Delete files in the generated tree that this run did not produce.""" removed = 0 for name in directories: @@ -86,7 +86,7 @@ def _sweep_generated(docs: Path, directories: list[str]) -> int: return removed -def _sweep_top_pages(docs: Path) -> int: +def sweep_top_pages(docs: Path) -> int: """Delete the pages at the root of the docs tree this run did not produce. The root holds only generated pages, one per stem (`cross-reference-*`, diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index 2b0504bf0..6aa876f11 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -33,7 +33,7 @@ try: import yaml except ImportError: yaml = None -from core.gitclone import _git_lines, _project_main_line +from core.gitclone import git_lines, project_main_line from resolve.review import ( ValidationResult, load_platform_hashes, @@ -58,14 +58,14 @@ def get_changed_files() -> list[str]: """ changed: list[str] = [] compared = False - project_base = _project_main_line() + project_base = project_main_line() remotes = [[project_base]] if project_base else [ [f"{remote}/{base}" for base in ("main", "master", "v2")] for remote in ("upstream", "origin") ] for candidates in remotes: for line in candidates: - committed = _git_lines("diff", "--name-only", f"{line}...HEAD") + committed = git_lines("diff", "--name-only", f"{line}...HEAD") if committed is None: continue compared = True @@ -73,9 +73,9 @@ def get_changed_files() -> list[str]: break if compared and changed: break - staged = _git_lines("diff", "--cached", "--name-only") - local = _git_lines("diff", "--name-only") - untracked = _git_lines("ls-files", "--others", "--exclude-standard", "--", "bios") + staged = git_lines("diff", "--cached", "--name-only") + local = git_lines("diff", "--name-only") + untracked = git_lines("ls-files", "--others", "--exclude-standard", "--", "bios") if staged is None and local is None and untracked is None: raise RuntimeError("git cannot read this checkout") for found in (staged, local, untracked): diff --git a/scripts/verify.py b/scripts/verify.py index d161bd30b..caff0e473 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -67,10 +67,10 @@ from model.safeparse import require_yaml from packs.coverage import verify_platform from packs.emulatorcheck import verify_emulator, verify_system from packs.report import ( - _NOT_FIRMWARE, - _core_required_missing, - _discrepancy_keys, - _split_undeclared, + NOT_FIRMWARE, + core_required_missing, + discrepancy_keys, + split_undeclared, print_emulator_result, print_platform_result, ) @@ -580,7 +580,7 @@ def _overall_summary(group_results: list[tuple[dict, list[str]]]) -> str: # Shipped files whose bytes contradict a declaration or a core's own # check: the body printed 19 of them under a last line that read clean. counts = { - " / ".join(group): len(_discrepancy_keys(r.get("details", []))) + " / ".join(group): len(discrepancy_keys(r.get("details", []))) for r, group in group_results } total = sum(counts.values()) @@ -592,7 +592,7 @@ def _overall_summary(group_results: list[tuple[dict, list[str]]]) -> str: holders: dict[str, list[str]] = {} for r, group in group_results: for name in sorted({ - u["name"] for u in _core_required_missing(_split_undeclared( + u["name"] for u in core_required_missing(split_undeclared( r.get("undeclared_files", []))[1]) }): holders.setdefault(name, []).append(" / ".join(group)) @@ -607,7 +607,7 @@ def _overall_summary(group_results: list[tuple[dict, list[str]]]) -> str: ) lines.append(f"{len(holders)} core file(s) a core cannot run without are " f"missing: {detail}") - for category, label in _NOT_FIRMWARE.items(): + for category, label in NOT_FIRMWARE.items(): counts = { " / ".join(group): len((r.get("missing_not_firmware") or {}).get(category, [])) for r, group in group_results diff --git a/tests/test_agnostic_scan.py b/tests/test_agnostic_scan.py index 19a823430..376505572 100644 --- a/tests/test_agnostic_scan.py +++ b/tests/test_agnostic_scan.py @@ -19,7 +19,7 @@ import tempfile import unittest from pathlib import Path -from model.profiles import load_emulator_profiles, _emulator_profiles_cache +from model.profiles import load_emulator_profiles, emulator_profiles_cache from resolve.localfile import resolve_local_file from packs import extras as packextras @@ -87,10 +87,10 @@ class AgnosticScanStaysInItsTree(unittest.TestCase): "base_destination": "", "systems": {}, } - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def _write_profile(self, body: str): @@ -98,7 +98,7 @@ class AgnosticScanStaysInItsTree(unittest.TestCase): return load_emulator_profiles(str(self.root / "emulators")) def _scan(self, profiles): - extras = packextras._collect_emulator_extras( + extras = packextras.collect_emulator_extras( self.config, str(self.root / "emulators"), self.db, set(), "", profiles, ) diff --git a/tests/test_agnostic_scan_mode.py b/tests/test_agnostic_scan_mode.py index 153af40be..438e90959 100644 --- a/tests/test_agnostic_scan_mode.py +++ b/tests/test_agnostic_scan_mode.py @@ -27,7 +27,7 @@ class ScanFollowsTheBuild(unittest.TestCase): from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras profiles = load_emulator_profiles("emulators") entry = next( @@ -38,7 +38,7 @@ class ScanFollowsTheBuild(unittest.TestCase): if entry is None or entry.get("mode") != "standalone": self.skipTest("armsx2 no longer declares a standalone proverb.zip") config = load_platform_config("retroarch") - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, "emulators", load_database("database.json"), set(), config.get("base_destination", ""), profiles, ) diff --git a/tests/test_archive_choice.py b/tests/test_archive_choice.py index fa89ca5d0..51918b44c 100644 --- a/tests/test_archive_choice.py +++ b/tests/test_archive_choice.py @@ -470,11 +470,11 @@ class ALooseEntryNamingItsArchive(unittest.TestCase): import yaml - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from packs.emulatorpack import generate_emulator_pack from packs.emulatorcheck import verify_emulator - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index f6d5032b8..d3c902504 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -222,7 +222,7 @@ class ScratchFilesGetThePlainMode(unittest.TestCase): from packs import finalize pack = self.dir / "Pack.zip" - with archive._writing_pack(str(pack)) as zf: + with archive.writing_pack(str(pack)) as zf: zf.writestr("a.bin", b"x") self.assertEqual(self._mode(pack), 0o644) os.chmod(pack, 0o600) @@ -315,9 +315,9 @@ class ATerminatedBuildLeavesNoScratch(unittest.TestCase): "import sys, time\n" "sys.path.insert(0, 'scripts')\n" "from core.cli import run_cli\n" - "from packs.archive import _writing_pack\n" + "from packs.archive import writing_pack\n" "def main():\n" - " with _writing_pack(sys.argv[1]) as zf:\n" + " with writing_pack(sys.argv[1]) as zf:\n" " zf.writestr('a.bin', b'x')\n" " print('writing', flush=True)\n" " time.sleep(60)\n" diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 8b89c404d..d44c04659 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -625,13 +625,13 @@ class APackIsSwappedInWhole(unittest.TestCase): def test_a_failed_build_keeps_the_previous_pack(self): import zipfile - from packs.archive import _writing_pack + from packs.archive import writing_pack directory = self._dir() pack = directory / "Pack.zip" with zipfile.ZipFile(pack, "w") as zf: zf.writestr("old.bin", b"complete") - with self.assertRaises(OSError), _writing_pack(str(pack)) as zf: + with self.assertRaises(OSError), writing_pack(str(pack)) as zf: zf.writestr("new.bin", b"half") raise OSError("disk full") with zipfile.ZipFile(pack) as zf: @@ -641,12 +641,12 @@ class APackIsSwappedInWhole(unittest.TestCase): def test_a_finished_build_replaces_it(self): import zipfile - from packs.archive import _writing_pack + from packs.archive import writing_pack directory = self._dir() pack = directory / "Pack.zip" pack.write_bytes(b"stale") - with _writing_pack(str(pack)) as zf: + with writing_pack(str(pack)) as zf: zf.writestr("new.bin", b"whole") with zipfile.ZipFile(pack) as zf: self.assertEqual(zf.namelist(), ["new.bin"]) @@ -823,7 +823,7 @@ class ADamagedArchiveIsNotPacked(unittest.TestCase): def test_the_rebuild_refusal_reaches_the_run(self): import zipfile - from packs.archive import DamagedArchiveError, _add_zip_to_pack + from packs.archive import DamagedArchiveError, add_zip_to_pack with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: source = Path(directory) / "set.zip" @@ -835,7 +835,7 @@ class ADamagedArchiveIsNotPacked(unittest.TestCase): pack = Path(directory) / "pack.zip" with zipfile.ZipFile(pack, "w") as target: with self.assertRaises(DamagedArchiveError) as caught: - _add_zip_to_pack(str(source), "set.zip", target) + add_zip_to_pack(str(source), "set.zip", target) self.assertNotIn("set.zip", target.namelist()) self.assertIsInstance(caught.exception, OSError) self.assertIn("set.zip", str(caught.exception)) @@ -849,7 +849,7 @@ class APackedArchiveKeepsItsBytes(unittest.TestCase): import hashlib import zipfile - from packs.archive import _add_zip_to_pack + from packs.archive import add_zip_to_pack with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: source = Path(directory) / "set.zip" @@ -857,7 +857,7 @@ class APackedArchiveKeepsItsBytes(unittest.TestCase): zf.writestr(zipfile.ZipInfo("rom.bin", (1999, 1, 2, 3, 4, 5)), b"rom" * 40) pack = Path(directory) / "pack.zip" with zipfile.ZipFile(pack, "w") as target: - _add_zip_to_pack(str(source), "set.zip", target) + add_zip_to_pack(str(source), "set.zip", target) with zipfile.ZipFile(pack) as packed: inner = packed.read("set.zip") self.assertEqual(hashlib.sha1(inner).hexdigest(), @@ -870,11 +870,11 @@ class PackReadmesSayWhatTheInstallerDoes(unittest.TestCase): RetroArch README offered only `| sh`, which Windows cannot run.""" def _guide(self, platform: str) -> str: - from packs.readme import _build_readme + from packs.readme import build_readme registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) install = registry["platforms"][platform].get("install") or {} - text = _build_readme(platform, platform, "", 1, 1, + text = build_readme(platform, platform, "", 1, 1, detect=install.get("detect", []), standalone_copies=install.get("standalone_copies", [])) return text[text.index("INSTALLATION"):text.index("TROUBLESHOOTING")] @@ -3351,30 +3351,30 @@ class APackNameFitsAFileName(unittest.TestCase): before writing anything, while verify --system snes reported.""" def test_a_long_selection_is_bounded_and_told_apart(self): - from scripts.packs.naming import MAX_PACK_NAME_BYTES, _bounded_pack_name + from scripts.packs.naming import MAX_PACK_NAME_BYTES, bounded_pack_name names = [f"Emulator_Number_{i}" for i in range(23)] - long_name = _bounded_pack_name(names, names, "_BIOS_Pack.zip") + long_name = bounded_pack_name(names, names, "_BIOS_Pack.zip") self.assertLessEqual(len(long_name.encode()), MAX_PACK_NAME_BYTES) self.assertTrue(long_name.startswith("Emulator_Number_0_and_22_more_")) - other = _bounded_pack_name(names, names[:-1] + ["x"], "_BIOS_Pack.zip") + other = bounded_pack_name(names, names[:-1] + ["x"], "_BIOS_Pack.zip") self.assertNotEqual(long_name, other) - self.assertEqual(_bounded_pack_name(["A", "B"], ["a", "b"], ".zip"), "A_B.zip") + self.assertEqual(bounded_pack_name(["A", "B"], ["a", "b"], ".zip"), "A_B.zip") def test_a_long_system_list_is_bounded(self): """Thirty systems joined made a 261-byte platform pack name.""" - from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, _system_tag + from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, system_tag systems = [f"vendor-console-number-{i}" for i in range(30)] - tag = _system_tag(systems) + tag = system_tag(systems) self.assertLessEqual(len(tag.encode()), MAX_SYSTEM_TAG_BYTES + 1) - self.assertNotEqual(tag, _system_tag(systems[:-1] + ["other-console"])) - self.assertEqual(_system_tag(["sony-playstation"]), "_Playstation") + self.assertNotEqual(tag, system_tag(systems[:-1] + ["other-console"])) + self.assertEqual(system_tag(["sony-playstation"]), "_Playstation") def test_two_systems_never_name_one_system(self): """sega-dreamcast,arcade and sega-dreamcast-arcade both wrote RetroArch_..._Dreamcast_Arcade.zip, and the second replaced the first.""" - from scripts.packs.naming import _system_tag + from scripts.packs.naming import system_tag pairs = [ (["sega-dreamcast", "arcade"], ["sega-dreamcast-arcade"]), @@ -3383,7 +3383,7 @@ class APackNameFitsAFileName(unittest.TestCase): ] for two, one in pairs: with self.subTest(two=two): - self.assertNotEqual(_system_tag(two), _system_tag(one)) + self.assertNotEqual(system_tag(two), system_tag(one)) def test_two_hash_lists_get_two_names(self): """--from-md5 named its pack after the context only: a second list @@ -3431,7 +3431,7 @@ class ARegionDroppedExtraBlocksNothing(unittest.TestCase): config = {"case_insensitive_fs": True, "base_destination": ""} def report(region_drops): - with mock.patch.object(packextras, "_collect_emulator_extras", + with mock.patch.object(packextras, "collect_emulator_extras", return_value=extras), \ mock.patch.object(packextras, "resolve_local_file", side_effect=lambda fe, *a, **k: ( @@ -3539,7 +3539,7 @@ class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase): with mock.patch("packs.gaps.find_undeclared_files", return_value=undeclared), \ mock.patch.object(packextras, "resolve_platform_cores", return_value=set()) as cores: - extras = packextras._collect_emulator_extras( + extras = packextras.collect_emulator_extras( config, "emulators", {"files": {}, "indexes": {}}, set(), "bios", {} ) self.assertEqual([e["source_profile"] for e in extras][:1], ["solarus"]) @@ -3714,7 +3714,7 @@ class AnArchiveShipsWholeUnderARegion(unittest.TestCase): def test_verify_filters_loose_files_only(self): source = script_source("verify.py") self.assertIn( - 'if fe.get("archive")\n or _resolve_destination(fe, standalone) not in region_drops', + 'if fe.get("archive")\n or resolve_destination(fe, standalone) not in region_drops', source, ) @@ -3972,7 +3972,7 @@ class ADataDirectoryIsWalkedOnce(unittest.TestCase): resolution cost names x tree on every pack build.""" def test_two_lookups_share_one_walk_and_keep_its_order(self): - from resolve.datadirs import forget_data_dir_index, _resolve_in_data_dirs + from resolve.datadirs import forget_data_dir_index, resolve_in_data_dirs with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as tmp: cache = Path(tmp) / "cache" @@ -3991,9 +3991,9 @@ class ADataDirectoryIsWalkedOnce(unittest.TestCase): return real_walk(top, *a, **k) with mock.patch.object(os, "walk", counting_walk): - first, _ = _resolve_in_data_dirs(["font.bin"], registry, + first, _ = resolve_in_data_dirs(["font.bin"], registry, lambda _p: "name_exact") - second, _ = _resolve_in_data_dirs(["other.bin"], registry, + second, _ = resolve_in_data_dirs(["other.bin"], registry, lambda _p: "name_exact") forget_data_dir_index() self.assertEqual(len(walks), 1) @@ -4223,7 +4223,7 @@ class TriageSurvivesAForgeRefusal(unittest.TestCase): mock.patch.object(triage, "select_repo", lambda p: object()), \ contextlib.redirect_stdout(out), \ contextlib.redirect_stderr(io.StringIO()): - triage._print_triage(args, selected, reports) + triage.print_triage(args, selected, reports) # A header row and a closing count frame the ranking. lines = out.getvalue().splitlines()[1:-1] self.assertEqual(len(lines), 2) @@ -4315,7 +4315,7 @@ class ASameNamedMemberIsNotTheFile(unittest.TestCase): (tmp / "bios").mkdir() with zipfile.ZipFile(tmp / "bios" / "extras.zip", "w") as zf: zf.writestr("files/other.ttf", b"MEMBER FONT") - names = crossref._build_supplemental_index(str(tmp / "data"), str(tmp / "bios")) + names = crossref.build_supplemental_index(str(tmp / "data"), str(tmp / "bios")) locations = crossref._supplemental_locations(str(tmp / "data"), str(tmp / "bios")) with mock.patch.object(crossref, "_supplemental_locations", lambda: locations): for fname, data in (("font.ttf", b"DATA FONT"), ("other.ttf", b"MEMBER FONT")): @@ -4481,7 +4481,7 @@ class EveryReadmeNamesItsFolder(unittest.TestCase): /storage/system, the folder the registry and the installer use.""" def test_the_registry_folder_is_in_the_guide(self): - from scripts.packs.readme import _build_readme + from scripts.packs.readme import build_readme registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) for name, entry in registry["platforms"].items(): @@ -4489,10 +4489,10 @@ class EveryReadmeNamesItsFolder(unittest.TestCase): if not folder: continue with self.subTest(platform=name): - text = _build_readme(name, name, "", 1, 1, + text = build_readme(name, name, "", 1, 1, detect=[{"os": "linux", "bios_path": folder}]) self.assertIn(folder, text) - lakka = _build_readme("lakka", "Lakka", "", 1, 1) + lakka = build_readme("lakka", "Lakka", "", 1, 1) self.assertNotIn("retroarch/system", lakka) @@ -4799,8 +4799,8 @@ class VerifyPacksSaysWhatItExcluded(unittest.TestCase): body = source[source.index("def _run_verify_packs"):] body = body[:body.index("\ndef ")] self.assertIn("bl_excluded, bl_absent) = result", body) - self.assertIn("_baseline_shortfall(bl_excluded, bl_absent)", body) - shortfall = source[source.index("def _baseline_shortfall"):] + self.assertIn("baseline_shortfall(bl_excluded, bl_absent)", body) + shortfall = source[source.index("def baseline_shortfall"):] self.assertIn("unsafe excluded", shortfall[:shortfall.index("\ndef ")]) self.assertNotIn("errors[:5]", body) self.assertNotRegex(body, r"result\[\d\]") @@ -4839,11 +4839,11 @@ class AFileToSourceIsAFileNotAName(unittest.TestCase): def test_rows_are_keyed_by_name_and_hash(self): source = script_source("generate_site.py") self.assertIn('key = (g["name"], g.get("identity") or f"emulator:{emu_name}")', source) - from scripts.packs.crossref import _first_hash + from scripts.packs.crossref import first_hash - self.assertEqual(_first_hash({"md5": ["AB", "cd"]}), "md5:ab") - self.assertEqual(_first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40) - self.assertEqual(_first_hash({}), "") + self.assertEqual(first_hash({"md5": ["AB", "cd"]}), "md5:ab") + self.assertEqual(first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40) + self.assertEqual(first_hash({}), "") @@ -4867,7 +4867,7 @@ class AFileCardSaysAllItKnows(unittest.TestCase): showed standalone_path, and gave no file an anchor to link to.""" def test_members_standalone_path_and_anchor(self): - from scripts.sitegen.emulatorcards import _render_emulator_file + from scripts.sitegen.emulatorcards import render_emulator_file entry = { "name": "neogeo.zip", "path": "neogeo.zip", "category": "bios_zip", @@ -4875,7 +4875,7 @@ class AFileCardSaysAllItKnows(unittest.TestCase): "contents": [{"name": f"m{i}.bin", "size": 1024, "crc32": f"{i:08x}"} for i in range(12)], } - text = "\n".join(_render_emulator_file( + text = "\n".join(render_emulator_file( entry, {"files": [entry]}, None, [entry], lambda f: True, "file-neogeo-zip", )) # The card is a heading with this id, linked by the heading's own @@ -5374,7 +5374,7 @@ class BundledFilesAreNotToSource(unittest.TestCase): entry = {"name": "n64.psh", "required": True, "in_repo": False, "category": "bios", "in_pack": True, "bundled": True} - self.assertEqual(packs_report._core_required_missing([entry]), []) + self.assertEqual(packs_report.core_required_missing([entry]), []) summary = verify._overall_summary( [({"severity_counts": {}, "undeclared_files": [entry]}, ["ROCKNIX"])] ) @@ -5473,12 +5473,12 @@ class AdlerValuesReadLikeTheDownloads(unittest.TestCase): byte-swapped ROM, so the raw ea3734fe in files.csv matched neither.""" def test_values_and_the_swap_are_stated(self): - from scripts.sitegen.emulatorcards import _render_emulator_file + from scripts.sitegen.emulatorcards import render_emulator_file entry = {"name": "dsp_rom.bin", "path": "dsp_rom.bin", "known_hash_adler32": ["0x66f334fe", "0xE789B5A5"], "adler32_byteswap": True} - text = "\n".join(_render_emulator_file( + text = "\n".join(render_emulator_file( entry, {"files": [entry]}, None, [entry], lambda f: True, "file-dsp", )) self.assertIn("`66f334fe`, `e789b5a5`", text) @@ -5553,11 +5553,11 @@ class UnsourceableCardSaysWhy(unittest.TestCase): and nothing else. The reason was only on the gaps page.""" def test_reason_and_link(self): - from scripts.sitegen.emulatorcards import _render_emulator_file + from scripts.sitegen.emulatorcards import render_emulator_file entry = {"name": "nds_firmware_modified.bin", "path": "x.bin", "unsourceable": "written by the firmware editor, so no dump of it exists"} - text = "\n".join(_render_emulator_file( + text = "\n".join(render_emulator_file( entry, {"files": [entry]}, None, [entry], lambda f: False, "file-x", )) self.assertIn("Not collected yet: written by the firmware editor", text) @@ -5599,10 +5599,10 @@ class CollectionCardsSayWhereToGetTheFile(unittest.TestCase): cards._RELEASE_ASSET_NAMES = None self.addCleanup(setattr, cards, "_RELEASE_ASSET_NAMES", None) self.assertEqual( - cards._fetch_url("bios/Sony/PlayStation/scph5501.bin"), + cards.fetch_url("bios/Sony/PlayStation/scph5501.bin"), "https://raw.githubusercontent.com/Abdess/retrobios/main/bios/Sony/PlayStation/scph5501.bin", ) - self.assertTrue(cards._fetch_url("bios/Arcade/MAME/MAME 0.174 Arcade XML.dat").endswith( + self.assertTrue(cards.fetch_url("bios/Arcade/MAME/MAME 0.174 Arcade XML.dat").endswith( "/releases/download/large-files/MAME.0.174.Arcade.XML.dat" )) @@ -5615,12 +5615,12 @@ class CollectionCardsCarryFullHashes(unittest.TestCase): def test_every_hash_in_full(self): from scripts.packs.crossref import FileConsumers - from scripts.sitegen.cards import _system_file_card + from scripts.sitegen.cards import system_file_card entry = {"name": "DUKE.RTS", "path": "bios/x/DUKE.RTS", "size": 10, "sha1": "a" * 40, "md5": "9d29f9673bbdb56068acf7645c13749c", "crc32": "504086c1", "sha256": "b" * 64} - text = "\n".join(_system_file_card(entry, FileConsumers({}, {}))) + text = "\n".join(system_file_card(entry, FileConsumers({}, {}))) for value in (entry["sha1"], entry["md5"], entry["crc32"], entry["sha256"]): self.assertIn(f'
    {value}
    ', text) @@ -5631,9 +5631,9 @@ class AHeldRevisionLinksItsBuildFile(unittest.TestCase): and the path a pinned link needs. 36 profiles carry one.""" def test_the_build_file_row(self): - from scripts.sitegen.emulatorcards import _build_rows + from scripts.sitegen.emulatorcards import build_rows - rows = _build_rows({"pin_frozen": "KNULLI builds this revision.", "pin_build": [{ + rows = build_rows({"pin_frozen": "KNULLI builds this revision.", "pin_build": [{ "platform": "knulli", "repo": "https://github.com/knulli-cfw/knulli-linux", "revision": "20260511", "path": "package/emulators/advanced_drastic/advanced_drastic.mk", "variable": "ADVANCED_DRASTIC_VERSION", "value": "eaf41ab9"}]}) @@ -5643,10 +5643,10 @@ class AHeldRevisionLinksItsBuildFile(unittest.TestCase): "at `20260511` sets `ADVANCED_DRASTIC_VERSION` |", rows) def test_a_build_read_at_a_recorded_commit_links(self): - from scripts.sitegen.emulatorcards import _build_rows + from scripts.sitegen.emulatorcards import build_rows pin = "46128cd252cdecae852a4d0bafa2aaf9d03ab563" - rows = _build_rows({"pin_build": [{ + rows = build_rows({"pin_build": [{ "platform": "retropie", "repo": "https://github.com/RetroPie/RetroPie-Setup", "revision": pin, "path": "scriptmodules/emulators/advmame-1.4.sh", "variable": "rp_module_repo", "value": "x"}]}) @@ -5669,14 +5669,14 @@ class AVariantCardSaysWhatToSaveItAs(unittest.TestCase): def test_the_name_to_save_it_under(self): from scripts.packs.crossref import FileConsumers - from scripts.sitegen.cards import _system_file_card + from scripts.sitegen.cards import system_file_card entry = {"name": "advision.zip", "size": 10, "sha1": "a" * 40, "path": "bios/Entex/Adventure Vision/.variants/advision.zip.1c086064"} - text = "\n".join(_system_file_card(entry, FileConsumers({}, {}))) + text = "\n".join(system_file_card(entry, FileConsumers({}, {}))) self.assertIn("Save as", text) self.assertIn("advision.zip.1c086064", text) - plain = "\n".join(_system_file_card( + plain = "\n".join(system_file_card( {**entry, "path": "bios/Entex/Adventure Vision/advision.zip"}, FileConsumers({}, {}))) self.assertNotIn("Save as", plain) @@ -5717,7 +5717,7 @@ class EmulatorCardsLinkTheCopyAndTheSection(unittest.TestCase): def test_copy_and_sections(self): from types import SimpleNamespace - from scripts.sitegen.emulatorcards import _render_emulator_file + from scripts.sitegen.emulatorcards import render_emulator_file sha1 = "ef9194ab4804aa0aa8540d846caf291b28331165" consumers = SimpleNamespace( @@ -5727,7 +5727,7 @@ class EmulatorCardsLinkTheCopyAndTheSection(unittest.TestCase): platform_systems={sha1: {"batocera": {"nintendo-gamecube"}}}, ) entry = {"name": "IPL.bin", "path": "GC/USA/IPL.bin"} - text = "\n".join(_render_emulator_file( + text = "\n".join(render_emulator_file( entry, {"files": [entry]}, consumers, [entry], lambda f: True, "file-ipl", "dolphin", )) self.assertIn("../systems/nintendo.md#sha1-ef9194ab4804", text) @@ -5801,9 +5801,9 @@ class SiteCodeSpansHoldTheirValue(unittest.TestCase): was read as markup.""" def test_a_backtick_cannot_close_the_span(self): - from scripts.sitegen.render import _code + from scripts.sitegen.render import code_span - span = _code("a``") + span = code_span("a``") self.assertEqual(span.count("`"), 2) self.assertTrue(span.startswith("`") and span.endswith("`")) @@ -5888,7 +5888,7 @@ class TheCollectionShipsADat(unittest.TestCase): Batocera reads.""" sys.path.insert(0, str(ROOT / "scripts" / "scraper")) from logiqx_parser import parse_logiqx - from scripts.sitegen.platformfiles import _platform_data_links + from scripts.sitegen.platformfiles import platform_data_links from scripts.sitegen.structured import platform_dat db = {"files": {"a" * 40: {"size": 4, "crc32": "8D8CB7E4", "md5": "1" * 32, @@ -5907,7 +5907,7 @@ class TheCollectionShipsADat(unittest.TestCase): ("bios", "dolphin-emu\\Sys\\GC\\font.bin")}) self.assertEqual(roms[("bios", "dc\\naomi2.zip")].md5, "1" * 32) self.assertEqual(roms[("bios", "dolphin-emu\\Sys\\GC\\font.bin")].md5, "3" * 32) - self.assertIn("[DAT](../downloads/dat/batocera.dat)", _platform_data_links("batocera")) + self.assertIn("[DAT](../downloads/dat/batocera.dat)", platform_data_links("batocera")) @@ -7128,7 +7128,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase): } return [ dest - for _src, dest in datatrees._data_directory_members( + for _src, dest in datatrees.data_directory_members( systems, registry, "retroarch", "", False, set(), set(), set(), required_only=required_only, ) @@ -7483,7 +7483,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase): def test_the_run_switch_is_inherited(self): from resolve import packfiles as packresolve - saved = packresolve._OFFLINE + saved = packresolve.OFFLINE packresolve.set_offline(True) try: with tempfile.TemporaryDirectory() as tmp, \ @@ -7891,14 +7891,14 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase): def test_a_held_file_out_of_reach_names_every_core_reading_it(self): """harm1.wad is a release asset: a checkout without it omits the file, and the omission named gzdoom alone where lzdoom reads it too.""" - from packs.manifestentry import _claim_cores + from packs.manifestentry import claim_cores extra = {"source_profile": "gzdoom", "other_claims": [ {"source_profile": "uzdoom"}, {"source_profile": "lzdoom"}]} - self.assertEqual(_claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"]) + self.assertEqual(claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"]) def test_a_missing_file_names_every_core_reading_it(self): - from packs.manifestentry import _record_absent + from packs.manifestentry import record_absent omitted: dict[str, dict] = {} @@ -7914,7 +7914,7 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase): omitted["SHARED.BIN"] = platform absent.append({"name": "SHARED.BIN", "destination": "SHARED.BIN", "source_profile": "raze"}) - _record_absent(absent, {}, "", set(), False, set(), omitted, record) + record_absent(absent, {}, "", set(), False, set(), omitted, record) self.assertEqual(omitted["NAPALM.GRP"]["cores"], ["eduke32", "raze"]) # A platform's own omission stays the platform's. self.assertIsNone(omitted["SHARED.BIN"]["cores"]) diff --git a/tests/test_case_insensitive_platforms.py b/tests/test_case_insensitive_platforms.py index d14dec32f..38175eb83 100644 --- a/tests/test_case_insensitive_platforms.py +++ b/tests/test_case_insensitive_platforms.py @@ -45,7 +45,7 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): def setUp(self): from model.platforms import _platform_config_cache - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache import generate_db tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) @@ -74,9 +74,9 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): "files": [{"name": "bios.col", "required": True}], })) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.addCleanup(_platform_config_cache.clear) - self.addCleanup(_emulator_profiles_cache.clear) + self.addCleanup(emulator_profiles_cache.clear) def _readme(self, systems: list[str]) -> str: from model.platforms import _platform_config_cache @@ -87,14 +87,14 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): }}})) _platform_config_cache.clear() texts: dict[str, str] = {} - real = platformpack._write_generated_member + real = platformpack.write_generated_member def capture(zf, arcname, text): texts[arcname] = text return real(zf, arcname, text) - platformpack._write_generated_member = capture - self.addCleanup(setattr, platformpack, "_write_generated_member", real) + platformpack.write_generated_member = capture + self.addCleanup(setattr, platformpack, "write_generated_member", real) with contextlib.redirect_stdout(io.StringIO()): platformpack.generate_pack( "p", "platforms", self.db, "bios", "", emulators_dir="emulators", diff --git a/tests/test_check_freshness.py b/tests/test_check_freshness.py index 499eb0149..c5ef38ace 100644 --- a/tests/test_check_freshness.py +++ b/tests/test_check_freshness.py @@ -400,7 +400,7 @@ class SiteNpmPins(unittest.TestCase): name = url.split("registry.npmjs.org/", 1)[1].rsplit("/latest", 1)[0] return {"version": latest[name]} with mock.patch.object(cf, "SITE_PACKAGE", package), \ - mock.patch.object(cf.upstream, "_http_json", side_effect=answer): + mock.patch.object(cf.upstream, "http_json", side_effect=answer): rows = {f.subject: f for f in cf._npm_findings()} self.assertEqual(rows["npm:astro"].status, cf.STALE) self.assertEqual(rows["npm:astro"].remote, "7.4.7") diff --git a/tests/test_content_checks.py b/tests/test_content_checks.py index 914fc0ba7..e268140e1 100644 --- a/tests/test_content_checks.py +++ b/tests/test_content_checks.py @@ -19,12 +19,12 @@ import tempfile import unittest from pathlib import Path -from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.profiles import emulator_profiles_cache, load_emulator_profiles from resolve.content import content_fits, size_fits, _masked_sha1_verdict from resolve.localfile import resolve_local_file from packs import extras as packextras from core.romdir import romdir_accepts, walk -from resolve.validation import _build_validation_index, check_file_validation +from resolve.validation import build_validation_index, check_file_validation REPO_ROOT = Path(__file__).resolve().parent.parent @@ -256,13 +256,13 @@ class ScannerVerifyManifestAgree(unittest.TestCase): " - name: \".nvm\"\n path: \"ps2/.nvm\"\n size: 1024\n" " - name: \".mec\"\n path: \"ps2/.mec\"\n size: 4\n" ) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(str(self.root / "emulators")) self.config = {"platform": "Demo", "verification_mode": "existence", "cores": ["demo", "anchor"], "base_destination": "", "systems": {}} def tearDown(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def accepted(self) -> set[str]: @@ -279,7 +279,7 @@ class ScannerVerifyManifestAgree(unittest.TestCase): "SCPH-70004.nvm", "246C.mec"}) def test_platform_pack_and_manifest_scan(self): - extras = packextras._collect_emulator_extras( + extras = packextras.collect_emulator_extras( self.config, str(self.root / "emulators"), self.db, set(), "", self.profiles, ) placed = {e["name"] for e in extras if e.get("source_profile") == "demo"} @@ -296,7 +296,7 @@ class ScannerVerifyManifestAgree(unittest.TestCase): self.assertEqual(names, self.accepted()) def test_resolver_name_step_and_validation_agree(self): - index = _build_validation_index(self.profiles_with_labels()) + index = build_validation_index(self.profiles_with_labels()) for name in self.IMAGES: path = str(self.root / "bios" / "PS2" / name) entry_ = {"name": name, "found_by": "content", "validation": ["romdir"], diff --git a/tests/test_core_data_trees.py b/tests/test_core_data_trees.py index b56071e90..c03b3f624 100644 --- a/tests/test_core_data_trees.py +++ b/tests/test_core_data_trees.py @@ -175,7 +175,7 @@ class AmberelecCarriesTheMachines(unittest.TestCase): trees = datatrees.core_data_trees(config, profiles, "amberelec", registry) refs: dict = {} members = dict( - (full, src) for src, full in datatrees._data_directory_members( + (full, src) for src, full in datatrees.data_directory_members( config.get("systems", {}), registry, "amberelec", config.get("base_destination", ""), False, set(), set(), set(), refs_out=refs, core_trees=trees, diff --git a/tests/test_core_file_fills_declaration.py b/tests/test_core_file_fills_declaration.py index 14d77fcaa..8417b0738 100644 --- a/tests/test_core_file_fills_declaration.py +++ b/tests/test_core_file_fills_declaration.py @@ -24,7 +24,7 @@ from unittest import mock import yaml -from model.profiles import _emulator_profiles_cache +from model.profiles import emulator_profiles_cache from model.platforms import load_platform_config from packs.platformpack import generate_pack from packs.coverage import verify_platform @@ -34,7 +34,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class ACoreFileFillsAFreeDeclaration(unittest.TestCase): def setUp(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, self.root, True) @@ -104,7 +104,7 @@ class AFileDeclaredUnderAnotherName(unittest.TestCase): declarations, took ROM as declared and never counted it.""" def test_the_report_lists_what_the_builder_packs(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) bios = root / "bios" / "Apple" / "IIgs" @@ -169,8 +169,8 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): })) db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {}, "by_path_suffix": {}}} - datatrees._MISSING_DATA_DIRS.clear() - self.addCleanup(datatrees._MISSING_DATA_DIRS.clear) + datatrees.MISSING_DATA_DIRS.clear() + self.addCleanup(datatrees.MISSING_DATA_DIRS.clear) with redirect_stdout(io.StringIO()): platformpack.generate_pack( "fakeplat", str(root / "platforms"), db, str(root / "bios"), @@ -178,9 +178,9 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): data_registry={"assets": {"local_cache": str(root / "absent")}}, offline=True, ) - self.assertEqual(datatrees._MISSING_DATA_DIRS, {"assets"}) + self.assertEqual(datatrees.MISSING_DATA_DIRS, {"assets"}) # main() starts each run with no notices, so the run itself records it. - with mock.patch.object(gp, "_main", lambda held: datatrees._MISSING_DATA_DIRS.add("assets")), \ + with mock.patch.object(gp, "_main", lambda held: datatrees.MISSING_DATA_DIRS.add("assets")), \ contextlib.redirect_stderr(io.StringIO()), \ self.assertRaises(SystemExit) as stop: gp.main() @@ -196,7 +196,7 @@ class AFileNobodyHoldsIsAnOmission(unittest.TestCase): def test_the_manifest_names_it(self): from packs.manifest import generate_manifest - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) for folder in ("platforms", "emulators", "bios"): @@ -237,7 +237,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase): def test_verify_reads_undeclared_files_as_the_builder_does(self): from packs import crossref - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) (root / "platforms").mkdir() @@ -255,7 +255,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase): db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {}, "by_path_suffix": {}}} config = load_platform_config("fakeplat", str(root / "platforms")) - with mock.patch.object(crossref, "_build_supplemental_index", + with mock.patch.object(crossref, "build_supplemental_index", lambda *a, **k: {"315-6146.bin"}): result = verify_platform(config, db, str(root / "emulators")) self.assertEqual( @@ -271,7 +271,7 @@ class TwoDeclarationsOfOnePath(unittest.TestCase): round, both must count the path once and met.""" def _run(self, first: str, second: str, spelling: str): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) bios = root / "bios" / "Maker" / "Console" @@ -322,7 +322,7 @@ class ANamelessWhitelistEntry(unittest.TestCase): missing in the pack and met in verify.""" def test_the_pack_counts_what_verify_counts(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) bios = root / "bios" / "Sony" / "PlayStation" diff --git a/tests/test_core_size_refusal.py b/tests/test_core_size_refusal.py index 0413c2e84..cf9fc894e 100644 --- a/tests/test_core_size_refusal.py +++ b/tests/test_core_size_refusal.py @@ -22,7 +22,7 @@ from pathlib import Path import yaml from model.platforms import _platform_config_cache -from model.profiles import load_emulator_profiles, _emulator_profiles_cache +from model.profiles import load_emulator_profiles, emulator_profiles_cache import generate_db from packs import manifest as packs_manifest from packs import platformpack @@ -90,12 +90,12 @@ class _Collection(unittest.TestCase): Path("emulators/sized.yml").write_text(SIZED) Path("emulators/unsized.yml").write_text(UNSIZED) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles("emulators") def tearDown(self): _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() os.chdir(self._cwd) self._tmp.cleanup() @@ -159,7 +159,7 @@ class SizeTheCoreRefuses(_Collection): Path("emulators/sized.yml").write_text( SIZED + " - name: ROM\n path: ROM\n size: 8\n validation: [size]\n" ) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles("emulators") self.assertTrue(self._report("sized")["in_repo"]) self.assertIn("ROM", self._pack_members()) diff --git a/tests/test_cross_reference_sources.py b/tests/test_cross_reference_sources.py index 976330fd4..8b88478ed 100644 --- a/tests/test_cross_reference_sources.py +++ b/tests/test_cross_reference_sources.py @@ -16,7 +16,7 @@ import tempfile import unittest from pathlib import Path -from packs.crossref import _build_supplemental_index, cross_reference, entry_source +from packs.crossref import build_supplemental_index, cross_reference, entry_source from cross_reference import print_report REPO_ROOT = Path(__file__).resolve().parent.parent @@ -77,7 +77,7 @@ class GapReportSources(unittest.TestCase): def test_a_directory_does_not_stand_for_a_file(self): with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: (Path(tmp) / "bios" / "cpcemu" / "ROM").mkdir(parents=True) - names = _build_supplemental_index(str(Path(tmp) / "data"), str(Path(tmp) / "bios")) + names = build_supplemental_index(str(Path(tmp) / "data"), str(Path(tmp) / "bios")) self.assertIsNone(entry_source({"name": "ROM"}, _index(data_names=names))) directory = {"name": "ROM", "type": "directory"} self.assertEqual(entry_source(directory, _index(data_names=names)), "data") diff --git a/tests/test_crypto_unique_data.py b/tests/test_crypto_unique_data.py index 5ef7ddf17..d9795ea76 100644 --- a/tests/test_crypto_unique_data.py +++ b/tests/test_crypto_unique_data.py @@ -55,12 +55,12 @@ def _rsa_sign(message: bytes) -> bytes: def _ecdsa_sign(message: bytes) -> bytes: - g = (ec._Gx, ec._Gy) - r = ec._ec_mul(_ECC_NONCE, g)[0] % ec._N + g = (ec.Gx, ec.Gy) + r = ec.ec_mul(_ECC_NONCE, g)[0] % ec.N digest = int.from_bytes(hashlib.sha256(message).digest(), "big") if ec._N_BITLEN < 256: digest >>= 256 - ec._N_BITLEN - s = (ec._modinv(_ECC_NONCE, ec._N) * (digest + r * _ECC_PRIVATE)) % ec._N + s = (ec._modinv(_ECC_NONCE, ec.N) * (digest + r * _ECC_PRIVATE)) % ec.N return r.to_bytes(30, "big") + s.to_bytes(30, "big") @@ -243,7 +243,7 @@ def _otp_plaintext( body[0x24:0x44] = _ECC_PRIVATE.to_bytes(0x20, "big") # Rebuild the certificate exactly as the verifier does, then sign it. - point = ec._ec_mul(_ECC_PRIVATE % ec._N, (ec._Gx, ec._Gy)) + point = ec.ec_mul(_ECC_PRIVATE % ec.N, (ec.Gx, ec.Gy)) pub_xy = point[0].to_bytes(30, "big") + point[1].to_bytes(30, "big") issuer = bytearray(0x40) issuer_str = ( @@ -264,7 +264,7 @@ def _otp_plaintext( def _root_public() -> bytes: - point = ec._ec_mul(_ECC_PRIVATE, (ec._Gx, ec._Gy)) + point = ec.ec_mul(_ECC_PRIVATE, (ec.Gx, ec.Gy)) return point[0].to_bytes(30, "big") + point[1].to_bytes(30, "big") diff --git a/tests/test_crypto_verify.py b/tests/test_crypto_verify.py index 048008150..2ebc8a28c 100644 --- a/tests/test_crypto_verify.py +++ b/tests/test_crypto_verify.py @@ -30,7 +30,7 @@ from core import sect233r1 as ec class FieldArithmetic(unittest.TestCase): """GF(2^233) with the reduction polynomial t^233 + t^74 + 1.""" - VALUES = (1, 2, 3, 0x1234567, ec._Gx, ec._Gy, (1 << 232) | 1) + VALUES = (1, 2, 3, 0x1234567, ec.Gx, ec.Gy, (1 << 232) | 1) def test_reduction_keeps_the_degree_below_the_field_size(self): for value in (1 << 300, (1 << 466) - 1, ec._F, ec._F << 5): @@ -49,7 +49,7 @@ class FieldArithmetic(unittest.TestCase): self.assertEqual(ec._gf_mul(a, b), ec._gf_mul(b, a)) def test_multiplication_is_associative(self): - a, b, c = ec._Gx, ec._Gy, 0x1234567 + a, b, c = ec.Gx, ec.Gy, 0x1234567 self.assertEqual( ec._gf_mul(ec._gf_mul(a, b), c), ec._gf_mul(a, ec._gf_mul(b, c)) ) @@ -79,44 +79,44 @@ class CurveParameters(unittest.TestCase): return left == right def test_the_generator_satisfies_the_curve_equation(self): - self.assertTrue(self._on_curve((ec._Gx, ec._Gy))) + self.assertTrue(self._on_curve((ec.Gx, ec.Gy))) def test_multiplying_the_generator_by_the_group_order_gives_infinity(self): """The definitive check on the point arithmetic.""" - self.assertIsNone(ec._ec_mul(ec._N, (ec._Gx, ec._Gy))) + self.assertIsNone(ec.ec_mul(ec.N, (ec.Gx, ec.Gy))) def test_scalar_multiplication_agrees_with_repeated_addition(self): - g = (ec._Gx, ec._Gy) + g = (ec.Gx, ec.Gy) accumulated = None for k in range(1, 9): accumulated = ec._ec_add(accumulated, g) - self.assertEqual(ec._ec_mul(k, g), accumulated, f"k={k}") + self.assertEqual(ec.ec_mul(k, g), accumulated, f"k={k}") def test_doubling_agrees_with_adding_a_point_to_itself(self): - g = (ec._Gx, ec._Gy) + g = (ec.Gx, ec.Gy) self.assertEqual(ec._ec_double(g), ec._ec_add(g, g)) def test_infinity_is_the_additive_identity(self): - g = (ec._Gx, ec._Gy) + g = (ec.Gx, ec.Gy) self.assertEqual(ec._ec_add(g, None), g) self.assertEqual(ec._ec_add(None, g), g) self.assertIsNone(ec._ec_add(None, None)) - self.assertIsNone(ec._ec_mul(0, g)) + self.assertIsNone(ec.ec_mul(0, g)) def test_modular_inverse_round_trips(self): - for a in (1, 2, 3, 12345, ec._N - 1): - self.assertEqual((a * ec._modinv(a, ec._N)) % ec._N, 1) + for a in (1, 2, 3, 12345, ec.N - 1): + self.assertEqual((a * ec._modinv(a, ec.N)) % ec.N, 1) def _sign(message: bytes, private: int, nonce: int) -> bytes: """ECDSA-SHA256 signing, so verification has something real to check.""" - g = (ec._Gx, ec._Gy) - point = ec._ec_mul(nonce, g) - r = point[0] % ec._N + g = (ec.Gx, ec.Gy) + point = ec.ec_mul(nonce, g) + r = point[0] % ec.N digest = int.from_bytes(hashlib.sha256(message).digest(), "big") if ec._N_BITLEN < 256: digest >>= 256 - ec._N_BITLEN - s = (ec._modinv(nonce, ec._N) * (digest + r * private)) % ec._N + s = (ec._modinv(nonce, ec.N) * (digest + r * private)) % ec.N return r.to_bytes(30, "big") + s.to_bytes(30, "big") @@ -127,7 +127,7 @@ class EcdsaVerification(unittest.TestCase): @classmethod def setUpClass(cls): - point = ec._ec_mul(cls.PRIVATE, (ec._Gx, ec._Gy)) + point = ec.ec_mul(cls.PRIVATE, (ec.Gx, ec.Gy)) cls.public = point[0].to_bytes(30, "big") + point[1].to_bytes(30, "big") cls.signature = _sign(cls.MESSAGE, cls.PRIVATE, cls.NONCE) @@ -149,7 +149,7 @@ class EcdsaVerification(unittest.TestCase): ) def test_another_public_key_is_rejected(self): - other = ec._ec_mul(self.PRIVATE + 1, (ec._Gx, ec._Gy)) + other = ec.ec_mul(self.PRIVATE + 1, (ec.Gx, ec.Gy)) encoded = other[0].to_bytes(30, "big") + other[1].to_bytes(30, "big") self.assertFalse( ec.ecdsa_verify_sha256(self.MESSAGE, self.signature, encoded) @@ -162,7 +162,7 @@ class EcdsaVerification(unittest.TestCase): ) def test_out_of_range_scalars_are_rejected(self): - for bad in (b"\x00" * 30, ec._N.to_bytes(30, "big")): + for bad in (b"\x00" * 30, ec.N.to_bytes(30, "big")): self.assertFalse( ec.ecdsa_verify_sha256(self.MESSAGE, bad + self.signature[30:], self.public) ) diff --git a/tests/test_dedup.py b/tests/test_dedup.py index 52f3d8447..da2bd1942 100644 --- a/tests/test_dedup.py +++ b/tests/test_dedup.py @@ -287,9 +287,9 @@ class PathPriority(unittest.TestCase): self.assertLess(primary, variant) def test_protected_directories_are_recognised(self): - self.assertTrue(nodedup._in_nodedup_dir("bios/RPG Maker/x/font.png")) - self.assertTrue(nodedup._in_nodedup_dir("bios/ScummVM/x/monkey.tbl")) - self.assertFalse(nodedup._in_nodedup_dir("bios/Sony/PlayStation/scph.bin")) + self.assertTrue(nodedup.in_nodedup_dir("bios/RPG Maker/x/font.png")) + self.assertTrue(nodedup.in_nodedup_dir("bios/ScummVM/x/monkey.tbl")) + self.assertFalse(nodedup.in_nodedup_dir("bios/Sony/PlayStation/scph.bin")) class TheNoDedupListIsPinned(unittest.TestCase): diff --git a/tests/test_deterministic_zip.py b/tests/test_deterministic_zip.py index 8d4163ab4..92e988467 100644 --- a/tests/test_deterministic_zip.py +++ b/tests/test_deterministic_zip.py @@ -13,7 +13,7 @@ import zipfile from pathlib import Path from scripts.core.deterministic_zip import ( - _FIXED_DATE_TIME, + FIXED_DATE_TIME, rebuild_zip_deterministic, verify_zip_determinism, ) @@ -67,7 +67,7 @@ class TestRebuild(unittest.TestCase): out, _ = self._rebuild() with zipfile.ZipFile(out) as zf: for info in zf.infolist(): - self.assertEqual(info.date_time, _FIXED_DATE_TIME) + self.assertEqual(info.date_time, FIXED_DATE_TIME) self.assertEqual(info.create_system, 0) self.assertEqual(info.external_attr, 0o100644 << 16) self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED) @@ -278,7 +278,7 @@ class TestPackDeterminism(unittest.TestCase): pack = self._build("out1") with zipfile.ZipFile(pack) as zf: dates = {i.date_time for i in zf.infolist()} - self.assertEqual(dates, {_FIXED_DATE_TIME}) + self.assertEqual(dates, {FIXED_DATE_TIME}) def test_generated_members_carry_the_fixed_epoch(self): pack = self._build("out1") @@ -291,7 +291,7 @@ class TestPackDeterminism(unittest.TestCase): ] self.assertTrue(generated, "pack should carry a generated README") for info in generated: - self.assertEqual(info.date_time, _FIXED_DATE_TIME) + self.assertEqual(info.date_time, FIXED_DATE_TIME) def _build_emulator(self, out_name: str) -> Path: from scripts.packs.emulatorpack import generate_emulator_pack @@ -313,14 +313,14 @@ class TestPackDeterminism(unittest.TestCase): " system: test-sys\n" " required: true\n" ) - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() path = generate_emulator_pack( ["detcore"], str(self.tmp / "emulators"), self.db, str(self.bios), str(out), offline=True, ) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.assertIsNotNone(path) return Path(path) @@ -337,7 +337,7 @@ class TestPackDeterminism(unittest.TestCase): def test_every_emulator_pack_member_carries_the_fixed_epoch(self): pack = self._build_emulator("emu1") with zipfile.ZipFile(pack) as zf: - self.assertEqual({i.date_time for i in zf.infolist()}, {_FIXED_DATE_TIME}) + self.assertEqual({i.date_time for i in zf.infolist()}, {FIXED_DATE_TIME}) def test_an_executable_source_stays_executable(self): """Pinning the mode stripped the bit the RetroDECK pack needs. @@ -393,7 +393,7 @@ class TestPackDeterminism(unittest.TestCase): inject_manifest(str(pack), manifest) with zipfile.ZipFile(pack) as zf: info = zf.getinfo("manifest.json") - self.assertEqual(info.date_time, _FIXED_DATE_TIME) + self.assertEqual(info.date_time, FIXED_DATE_TIME) @@ -421,7 +421,7 @@ class ManifestInjectionIsAtomic(unittest.TestCase): zf.fp.flush() raise KeyboardInterrupt - with mock.patch.object(finalize, "_write_generated_member", die), \ + with mock.patch.object(finalize, "write_generated_member", die), \ self.assertRaises(KeyboardInterrupt): finalize.inject_manifest(str(pack), {"files": ["x"] * 2000}) self.assertEqual(pack.read_bytes(), before) @@ -437,14 +437,14 @@ class PackMemberCompression(unittest.TestCase): the packs' size.""" def _pack(self, tmp: Path, name: str) -> Path: - from scripts.packs.archive import _add_pack_member + from scripts.packs.archive import add_pack_member source = tmp / "member" source.write_bytes(b"\x00" * 4096) pack = tmp / name with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as zf: for arcname in ("bios/a.zip", "bios/b.PNG", "bios/c.bin", "bios/d.pk3"): - _add_pack_member(zf, str(source), arcname) + add_pack_member(zf, str(source), arcname) return pack def test_compressed_formats_are_stored_and_the_rest_deflated(self): diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index c01a5b3ac..c149206e2 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -25,7 +25,7 @@ try: import jsonschema except ImportError: jsonschema = None -from model.profiles import load_emulator_profiles, _emulator_profiles_cache +from model.profiles import load_emulator_profiles, emulator_profiles_cache from resolve.directories import directory_members import generate_db from packs import emulatorpack @@ -92,10 +92,10 @@ class DirectoryFixture(unittest.TestCase): (self.platforms / "_registry.yml").write_text( yaml.dump({"platforms": {"demo": {"config": "demo.yml"}}}) ) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def _add(self, relative: str, payload: bytes) -> None: @@ -125,7 +125,7 @@ class DirectoryFixture(unittest.TestCase): def _profiles(self, body: str = PROFILE) -> dict: (self.emulators / "demo.yml").write_text(body) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() return load_emulator_profiles(str(self.emulators)) diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index ec86b9aac..a5110cf96 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -479,7 +479,7 @@ class ValidationIndexScope(unittest.TestCase): source = inspect.getsource(coverage.verify_platform) self.assertRegex(source, r"plat_cores = resolve_platform_cores\(config, profiles\)") - self.assertIn("_build_validation_index(platform_profiles)", source) + self.assertIn("build_validation_index(platform_profiles)", source) section = _section(_page("verification-modes.md"), "Validation index") self.assertIn("resolve_platform_cores", section) self.assertNotIn("reads all emulator profiles", section) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index f217d5ccf..f0ae49c21 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -43,7 +43,7 @@ from model.platforms import load_platform_config from resolve.localfile import resolve_local_file from resolve.cores import resolve_platform_cores from resolve.truth import diff_platform_truth, generate_platform_truth -from resolve.validation import _build_validation_index, check_file_validation, filter_files_by_mode +from resolve.validation import build_validation_index, check_file_validation, filter_files_by_mode from packs.verdicts import Severity, Status from packs.gaps import find_exclusion_notes, find_undeclared_files from packs.emulatorcheck import verify_emulator @@ -76,9 +76,9 @@ class TestE2E(unittest.TestCase): def setUp(self): # Clear emulator profile cache to avoid stale data between tests - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.root = tempfile.mkdtemp() self.bios_dir = os.path.join(self.root, "bios") @@ -1263,7 +1263,7 @@ class TestE2E(unittest.TestCase): def test_70_validation_index_built(self): """Validation index extracts checks from emulator profiles.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) self.assertIn("present_req.bin", index) self.assertIn("size", index["present_req.bin"]["checks"]) self.assertIn(16, index["present_req.bin"]["sizes"]) @@ -1273,7 +1273,7 @@ class TestE2E(unittest.TestCase): def test_71_validation_size_pass(self): """File with correct size passes validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["present_req.bin"]["path"] reason = check_file_validation(path, "present_req.bin", index) self.assertIsNone(reason) @@ -1281,7 +1281,7 @@ class TestE2E(unittest.TestCase): def test_72_validation_size_fail(self): """File with wrong size fails validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["present_opt.bin"]["path"] result = check_file_validation(path, "present_opt.bin", index) self.assertIsNotNone(result) @@ -1292,7 +1292,7 @@ class TestE2E(unittest.TestCase): def test_73_validation_crc32_pass(self): """File with correct CRC32 passes validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["correct_hash.bin"]["path"] reason = check_file_validation(path, "correct_hash.bin", index) self.assertIsNone(reason) @@ -1300,7 +1300,7 @@ class TestE2E(unittest.TestCase): def test_74_validation_crc32_fail(self): """File with wrong CRC32 fails validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["no_md5.bin"]["path"] result = check_file_validation(path, "no_md5.bin", index) self.assertIsNotNone(result) @@ -1325,7 +1325,7 @@ class TestE2E(unittest.TestCase): def test_77_validation_crc32_leading_zero(self): """CRC32 starting with '0' must not be truncated (lstrip regression).""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["leading_zero_crc.bin"]["path"] reason = check_file_validation(path, "leading_zero_crc.bin", index) self.assertIsNone(reason) @@ -1346,13 +1346,13 @@ class TestE2E(unittest.TestCase): ], }, } - index = _build_validation_index(profiles) + index = build_validation_index(profiles) self.assertEqual(index["shared.bin"]["sizes"], {512, 1024}) def test_79_validation_md5_pass(self): """File with correct MD5 passes validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["correct_hash.bin"]["path"] reason = check_file_validation(path, "correct_hash.bin", index) self.assertIsNone(reason) @@ -1360,7 +1360,7 @@ class TestE2E(unittest.TestCase): def test_80_validation_md5_fail(self): """File with wrong MD5 fails validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["alias_target.bin"]["path"] result = check_file_validation(path, "alias_target.bin", index) self.assertIsNotNone(result) @@ -1371,7 +1371,7 @@ class TestE2E(unittest.TestCase): def test_81_validation_index_has_md5_sha1(self): """Validation index stores md5 and sha1 when declared.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) self.assertIn("md5", index["correct_hash.bin"]["checks"]) self.assertIn("sha1", index["correct_hash.bin"]["checks"]) self.assertIsNotNone(index["correct_hash.bin"]["md5"]) @@ -1380,7 +1380,7 @@ class TestE2E(unittest.TestCase): def test_82_validation_adler32_pass(self): """File with correct adler32 passes validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["present_req.bin"]["path"] reason = check_file_validation(path, "present_req.bin", index) self.assertIsNone(reason) @@ -1388,7 +1388,7 @@ class TestE2E(unittest.TestCase): def test_83_validation_min_max_size_pass(self): """File within min/max size range passes validation.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) path = self.files["present_req.bin"]["path"] reason = check_file_validation(path, "present_req.bin", index) self.assertIsNone(reason) @@ -1399,7 +1399,7 @@ class TestE2E(unittest.TestCase): def test_84_validation_crypto_tracked(self): """Signature/crypto checks are tracked as non-reproducible.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) # correct_hash.bin has [size, signature] self.assertIn("signature", index["correct_hash.bin"]["crypto_only"]) # Size check still applies despite signature being non-reproducible @@ -1410,7 +1410,7 @@ class TestE2E(unittest.TestCase): def test_76_validation_no_effect_when_no_field(self): """Files without validation field are unaffected.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) # wrong_hash.bin has no validation in any profile path = self.files["wrong_hash.bin"]["path"] reason = check_file_validation(path, "wrong_hash.bin", index) @@ -2063,7 +2063,7 @@ class TestE2E(unittest.TestCase): def test_111_validation_index_per_emulator(self): """Validation index includes per-emulator detail for ground truth.""" profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) entry = index["present_req.bin"] self.assertIn("per_emulator", entry) pe = entry["per_emulator"] @@ -2077,7 +2077,7 @@ class TestE2E(unittest.TestCase): from resolve.validation import build_ground_truth profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) gt = build_ground_truth("present_req.bin", index) self.assertIsInstance(gt, list) self.assertTrue(len(gt) >= 1) @@ -2094,7 +2094,7 @@ class TestE2E(unittest.TestCase): from resolve.validation import build_ground_truth profiles = load_emulator_profiles(self.emulators_dir) - index = _build_validation_index(profiles) + index = build_validation_index(profiles) gt = build_ground_truth("nonexistent.bin", index) self.assertEqual(gt, []) @@ -2431,12 +2431,12 @@ class TestE2E(unittest.TestCase): self.assertFalse(any("present_opt.bin" in n for n in names)) def test_133_platform_system_filter_normalized(self): - """_norm_system_id normalization matches with manufacturer prefix.""" - from model.systems import _norm_system_id + """norm_system_id normalization matches with manufacturer prefix.""" + from model.systems import norm_system_id self.assertEqual( - _norm_system_id("sony-playstation"), - _norm_system_id("playstation"), + norm_system_id("sony-playstation"), + norm_system_id("playstation"), ) def test_134_list_systems_platform_context(self): @@ -3069,38 +3069,38 @@ class TestE2E(unittest.TestCase): self.assertEqual(records[0]["name"], "good.bin") def test_157_path_conflict_helpers(self): - """_has_path_conflict detects file/directory naming collisions.""" - from packs.paths import _has_path_conflict, _register_path + """has_path_conflict detects file/directory naming collisions.""" + from packs.paths import has_path_conflict, register_path seen_files: set[str] = set() seen_parents: set[str] = set() # Register system/SGB1.sfc as a file - _register_path("system/SGB1.sfc", seen_files, seen_parents) + register_path("system/SGB1.sfc", seen_files, seen_parents) # Adding system/SGB1.sfc/program.rom should conflict (parent is a file) self.assertTrue( - _has_path_conflict("system/SGB1.sfc/program.rom", seen_files, seen_parents) + has_path_conflict("system/SGB1.sfc/program.rom", seen_files, seen_parents) ) # Adding system/other.bin should not conflict self.assertFalse( - _has_path_conflict("system/other.bin", seen_files, seen_parents) + has_path_conflict("system/other.bin", seen_files, seen_parents) ) # Reverse: register a nested path first, then check flat seen_files2: set[str] = set() seen_parents2: set[str] = set() - _register_path("system/SGB2.sfc/program.rom", seen_files2, seen_parents2) + register_path("system/SGB2.sfc/program.rom", seen_files2, seen_parents2) # Adding system/SGB2.sfc as a file should conflict (it's a directory) self.assertTrue( - _has_path_conflict("system/SGB2.sfc", seen_files2, seen_parents2) + has_path_conflict("system/SGB2.sfc", seen_files2, seen_parents2) ) # Adding system/SGB2.sfc/boot.rom should not conflict (sibling in same dir) self.assertFalse( - _has_path_conflict("system/SGB2.sfc/boot.rom", seen_files2, seen_parents2) + has_path_conflict("system/SGB2.sfc/boot.rom", seen_files2, seen_parents2) ) def test_158_pack_skips_file_directory_conflict(self): @@ -3264,11 +3264,11 @@ class TestE2E(unittest.TestCase): def test_164_pack_extras_use_archive_name(self): """Pack extras for archived files use archive name, not individual ROM.""" - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras config = load_platform_config("test_existence", self.platforms_dir) profiles = load_emulator_profiles(self.emulators_dir) - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, self.emulators_dir, self.db, @@ -3286,11 +3286,11 @@ class TestE2E(unittest.TestCase): def test_165_pack_extras_multi_dest_cross_ref(self): """Same file at different paths from two profiles produces both destinations.""" - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras config = load_platform_config("test_existence", self.platforms_dir) profiles = load_emulator_profiles(self.emulators_dir) - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, self.emulators_dir, self.db, @@ -3306,13 +3306,13 @@ class TestE2E(unittest.TestCase): def test_166_pack_extras_multi_dest_platform_declared(self): """Profile with path different from platform destination adds alternative.""" - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras config = load_platform_config("test_existence", self.platforms_dir) profiles = load_emulator_profiles(self.emulators_dir) # Simulate platform already having present_req.bin at root seen = {"present_req.bin"} - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, self.emulators_dir, self.db, @@ -3396,9 +3396,9 @@ class TestE2E(unittest.TestCase): _yaml.dump(profile, f) # Clear profile cache so fresh load picks up our file - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(self.emulators_dir) config = {"cores": ["testcore"]} @@ -3426,7 +3426,7 @@ class TestE2E(unittest.TestCase): def test_169_generate_truth_mode_filtering(self): """generate_platform_truth excludes standalone-only files for all_libretro.""" import yaml as _yaml - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache profile = { "emulator": "DualMode", @@ -3461,7 +3461,7 @@ class TestE2E(unittest.TestCase): with open(os.path.join(self.emulators_dir, "dualmode.yml"), "w") as f: _yaml.dump(profile, f) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(self.emulators_dir) config = {"cores": "all_libretro"} @@ -3476,7 +3476,7 @@ class TestE2E(unittest.TestCase): def test_170_generate_truth_standalone_cores(self): """generate_platform_truth uses standalone mode for standalone_cores.""" import yaml as _yaml - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache profile = { "emulator": "DualCore", @@ -3503,7 +3503,7 @@ class TestE2E(unittest.TestCase): with open(os.path.join(self.emulators_dir, "dualcore.yml"), "w") as f: _yaml.dump(profile, f) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(self.emulators_dir) config = { "cores": ["dualcore"], @@ -3519,7 +3519,7 @@ class TestE2E(unittest.TestCase): def test_171_generate_truth_dedup_required_wins(self): """Dedup merges cores and required=True wins over required=False.""" import yaml as _yaml - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache core_a = { "emulator": "CoreA", @@ -3555,7 +3555,7 @@ class TestE2E(unittest.TestCase): with open(os.path.join(self.emulators_dir, f"{name}.yml"), "w") as f: _yaml.dump(data, f) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(self.emulators_dir) config = {"cores": ["core_a", "core_b"]} @@ -3574,7 +3574,7 @@ class TestE2E(unittest.TestCase): def test_172_generate_truth_coverage_metadata(self): """Coverage tracks profiled vs unprofiled cores.""" import yaml as _yaml - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache profile = { "emulator": "ProfiledCore", @@ -3588,7 +3588,7 @@ class TestE2E(unittest.TestCase): with open(os.path.join(self.emulators_dir, "profiled_core.yml"), "w") as f: _yaml.dump(profile, f) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(self.emulators_dir) config = {"cores": ["profiled_core", "unprofiled_core"]} @@ -4398,9 +4398,9 @@ class TestE2E(unittest.TestCase): # No profile for core_b (unprofiled) # Clear cache so the new profile is picked up - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(self.emulators_dir) self.assertIn("core_a", profiles) self.assertNotIn("core_b", profiles) @@ -4652,11 +4652,11 @@ class TestE2E(unittest.TestCase): def test_181_agnostic_extras_scan(self): """Agnostic profiles add all matching DB files as extras.""" - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras config = load_platform_config("test_existence", self.platforms_dir) profiles = load_emulator_profiles(self.emulators_dir) - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, self.emulators_dir, self.db, @@ -4674,10 +4674,10 @@ class TestE2E(unittest.TestCase): self.assertTrue(e.get("agnostic_scan", False)) def test_182_agnostic_rename_readme(self): - """_build_agnostic_rename_readme generates correct text.""" - from packs.readme import _build_agnostic_rename_readme + """build_agnostic_rename_readme generates correct text.""" + from packs.readme import build_agnostic_rename_readme - result = _build_agnostic_rename_readme( + result = build_agnostic_rename_readme( "dsi_nand.bin", "DSi_Nand_AUS.bin", ["DSi_Nand_EUR.bin", "DSi_Nand_USA.bin"], @@ -5035,20 +5035,20 @@ struct BurnDriver BurnDrvneogeo = { def test_201_collect_emulator_extras_include_all(self): """include_all=True passes through to find_undeclared_files.""" - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras config = self._load_config("test_existence") profiles = load_emulator_profiles(self.emulators_dir) base_dest = config.get("base_destination", "") # Default call must succeed without TypeError - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, self.emulators_dir, self.db, set(), base_dest, profiles ) self.assertIsInstance(extras, list) # include_all=True must be accepted and return a list - all_extras = _collect_emulator_extras( + all_extras = collect_emulator_extras( config, self.emulators_dir, self.db, set(), base_dest, profiles, include_all=True, ) @@ -6125,9 +6125,9 @@ struct BurnDriver BurnDrvneogeo = { def test_every_narrowing_names_itself_and_says_so(self): """A dimension that removes files must show in the pack name and in the - README. Both are built from _narrowings, so this holds for any new one.""" - from packs.readme import _build_readme - from packs.naming import _narrowings + README. Both are built from pack_narrowings, so this holds for any new one.""" + from packs.readme import build_readme + from packs.naming import pack_narrowings dimensions = [ {"source": "platform"}, @@ -6139,7 +6139,7 @@ struct BurnDriver BurnDrvneogeo = { {"no_game_data": True}, ] for kwargs in dimensions: - applied = _narrowings( + applied = pack_narrowings( kwargs.get("source", "full"), kwargs.get("regions"), kwargs.get("target_name"), @@ -6151,7 +6151,7 @@ struct BurnDriver BurnDrvneogeo = { tag, label = applied[0] self.assertTrue(tag.startswith("_") and len(tag) > 1, kwargs) self.assertTrue(label.strip(), kwargs) - readme = _build_readme("p", "P", "", 1, 1, narrowings=applied) + readme = build_readme("p", "P", "", 1, 1, narrowings=applied) self.assertIn("PACK TYPE: Narrowed", readme) self.assertIn(label, readme) @@ -6321,7 +6321,7 @@ struct BurnDriver BurnDrvneogeo = { import inspect from packs import integrity as packverify - from packs.naming import _narrows_contents, _narrowings + from packs.naming import narrows_contents, pack_narrowings source = inspect.getsource(packverify.verify_pack_against_platform) self.assertIn( @@ -6342,18 +6342,18 @@ struct BurnDriver BurnDrvneogeo = { # And the pack must not be skipped instead: skipping checks nothing. for target in ("nintendo-switch", "switch", "rpi4"): - tag = _narrowings("full", None, target, False, False)[0][0] + tag = pack_narrowings("full", None, target, False, False)[0][0] self.assertFalse( - _narrows_contents(f"Platform_1.0{tag}_BIOS_Pack.zip"), + narrows_contents(f"Platform_1.0{tag}_BIOS_Pack.zip"), f"a pack built for {target} would skip conformance entirely", ) def test_standalone_mode_names_itself(self): """--emulator --standalone ships a different file set, and without a tag it overwrote the pack built without it.""" - from packs.naming import _narrowings + from packs.naming import pack_narrowings - applied = _narrowings("full", None, None, False, False, standalone=True) + applied = pack_narrowings("full", None, None, False, False, standalone=True) self.assertEqual([tag for tag, _l in applied], ["_Standalone"]) def test_every_name_builder_uses_the_same_list(self): @@ -6372,7 +6372,7 @@ struct BurnDriver BurnDrvneogeo = { '("_Platform_", "_Truth_"', ): self.assertNotIn(hand_rolled, source, hand_rolled) - self.assertGreaterEqual(source.count("_narrowings("), 8) + self.assertGreaterEqual(source.count("pack_narrowings("), 8) def test_a_narrowed_system_pack_does_not_take_the_full_name(self): """Every dimension has to show in the filename or two builds collide. @@ -6473,18 +6473,18 @@ struct BurnDriver BurnDrvneogeo = { self.assertFalse(os.listdir(out) if os.path.isdir(out) else []) def test_a_full_pack_is_not_announced_as_narrowed(self): - from packs.readme import _build_readme - from packs.naming import _narrowings + from packs.readme import build_readme + from packs.naming import pack_narrowings - self.assertEqual(_narrowings("full", None, None, False, False), []) + self.assertEqual(pack_narrowings("full", None, None, False, False), []) self.assertNotIn( - "PACK TYPE: Narrowed", _build_readme("p", "P", "", 1, 1) + "PACK TYPE: Narrowed", build_readme("p", "P", "", 1, 1) ) def test_system_filter_is_announced_too(self): - from packs.readme import _build_readme + from packs.readme import build_readme - readme = _build_readme( + readme = build_readme( "p", "P", "", 1, 1, system_filter=["sony-playstation"] ) self.assertIn("PACK TYPE: Narrowed", readme) @@ -6603,7 +6603,7 @@ struct BurnDriver BurnDrvneogeo = { self.assertEqual(len(result), len(annotated)) def test_narrowed_variants_skip_conformance(self): - from packs.naming import _narrows_contents + from packs.naming import narrows_contents for narrowed in ( "EmuDeck_2.3.8_Required_BIOS_Pack.zip", @@ -6611,14 +6611,14 @@ struct BurnDriver BurnDrvneogeo = { "EmuDeck_2.3.8_Truth_Required_BIOS_Pack.zip", "EmuDeck_2.3.8_NorthAmerica_Required_BIOS_Pack.zip", ): - self.assertTrue(_narrows_contents(narrowed), narrowed) + self.assertTrue(narrows_contents(narrowed), narrowed) for full in ( "EmuDeck_2.3.8_BIOS_Pack.zip", "EmuDeck_2.3.8_NorthAmerica_BIOS_Pack.zip", "RetroArch_v1.22.2_Switch_BIOS_Pack.zip", ): - self.assertFalse(_narrows_contents(full), full) + self.assertFalse(narrows_contents(full), full) def test_target_tag_formats_hardware_names(self): from packs.naming import _target_tag @@ -6643,9 +6643,9 @@ struct BurnDriver BurnDrvneogeo = { self.assertIn("Switch", name) def test_readme_region_section_lists_fallback_systems(self): - from packs.readme import _build_readme + from packs.readme import build_readme - text = _build_readme( + text = build_readme( "regionplat", "RegionPlat", "", @@ -6661,9 +6661,9 @@ struct BurnDriver BurnDrvneogeo = { self.assertNotIn("All are included", text) def test_readme_without_region_keeps_the_regional_note(self): - from packs.readme import _build_readme + from packs.readme import build_readme - text = _build_readme("regionplat", "RegionPlat", "", 10, 2) + text = build_readme("regionplat", "RegionPlat", "", 10, 2) self.assertNotIn("PACK TYPE: Region Filtered", text) self.assertIn("All are included", text) @@ -6794,9 +6794,9 @@ class OneOfASearchList(unittest.TestCase): """ def setUp(self): - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() repo = Path(__file__).resolve().parent.parent (repo / "tmp").mkdir(exist_ok=True) self.root = Path(tempfile.mkdtemp(dir=repo / "tmp")) @@ -7060,9 +7060,9 @@ class AnArchiveIsAMemberOfASet(unittest.TestCase): def _fixture(self, held: bool) -> dict: import zlib - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() repo = Path(__file__).resolve().parent.parent (repo / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=repo / "tmp")) diff --git a/tests/test_emulator_pack_counts.py b/tests/test_emulator_pack_counts.py index 949d676d2..7cda60780 100644 --- a/tests/test_emulator_pack_counts.py +++ b/tests/test_emulator_pack_counts.py @@ -80,11 +80,11 @@ class APlaceholderIsAnsweredByEvidence(unittest.TestCase): import yaml - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from packs.emulatorpack import generate_emulator_pack from packs.emulatorcheck import verify_emulator - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) diff --git a/tests/test_export_report.py b/tests/test_export_report.py index ed987ef32..4e2bd4385 100644 --- a/tests/test_export_report.py +++ b/tests/test_export_report.py @@ -97,9 +97,9 @@ class CorrectedFilesPage(unittest.TestCase): for platform in ("recalbox", "retropie"): self.assertIn(f'href="api/v1/exports/{platform}.json"', self.page) source = script_source("generate_site.py") - publish = source[source.index("def _publish_manifests("):] + publish = source[source.index("def publish_manifests("):] publish = publish[:publish.index("\ndef ")] - self.assertIn('(_REPO_ROOT / "exports").glob("*.json")', publish) + self.assertIn('(REPO_ROOT / "exports").glob("*.json")', publish) self.assertIn('exports = api / "exports"', publish) def test_several_files_link_to_their_directory(self): diff --git a/tests/test_extra_identity.py b/tests/test_extra_identity.py index 45fe121f8..0d114f80d 100644 --- a/tests/test_extra_identity.py +++ b/tests/test_extra_identity.py @@ -15,7 +15,7 @@ import unittest from pathlib import Path from model.profiles import PROFILE_IDENTITY_FIELDS -from packs.extras import _collect_emulator_extras +from packs.extras import collect_emulator_extras from packs.gaps import find_undeclared_files REPO_ROOT = Path(__file__).resolve().parents[1] @@ -46,7 +46,7 @@ class IdentityTravels(unittest.TestCase): "by_crc32": {"12345678": "s1"}}, } report = find_undeclared_files(config, "emulators", db, emu_profiles={"np2kai": profile}) - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, "emulators", db, set(), "", {"np2kai": profile}, include_all=True ) for label, item in (("report", report[0]), ("extra", extras[0])): @@ -91,7 +91,7 @@ class UnsourceableIsNoCopy(unittest.TestCase): "by_crc32": {"c1": "s1"}, "by_path_suffix": {"zc210/sf2/default.sf2": ["s1"]}}, } - extras = _collect_emulator_extras(config, "emulators", db, set(), "", profiles) + extras = collect_emulator_extras(config, "emulators", db, set(), "", profiles) self.assertEqual( [(e["source_profile"], e["destination"]) for e in extras], [("zc210", "zc210/sf2/default.sf2")], @@ -117,7 +117,7 @@ class BareNameIsADestination(unittest.TestCase): "indexes": {"by_name": {"syscard1.pce": ["s1"]}, "by_md5": {"m1": "s1"}, "by_crc32": {"c1": "s1"}, "by_path_suffix": {}}, } - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, "emulators", db, {"pcenginecd/syscard1.pce"}, "", profiles ) self.assertIn("syscard1.pce", [e["destination"] for e in extras]) @@ -142,7 +142,7 @@ class ArchiveMembersStayInside(unittest.TestCase): "indexes": {"by_name": {"msx.rom": ["s1"]}, "by_md5": {"m1": "s1"}, "by_crc32": {"c1": "s1"}, "by_path_suffix": {}}, } - extras = _collect_emulator_extras(config, "emulators", db, set(), "", profiles) + extras = collect_emulator_extras(config, "emulators", db, set(), "", profiles) loose = [e for e in extras if e["destination"] == "msx.rom"] self.assertEqual([e["source_profile"] for e in loose], ["zesarux"]) diff --git a/tests/test_find_pinned_revision.py b/tests/test_find_pinned_revision.py index 6cb3d3a91..9c0f5bb4d 100644 --- a/tests/test_find_pinned_revision.py +++ b/tests/test_find_pinned_revision.py @@ -27,7 +27,7 @@ class ThePinnedRevisionIsInTheHistory(unittest.TestCase): def fetch(url, *_a, **_k): return next(data for sha, data in blobs.items() if f"/{sha}/" in url) - with mock.patch.object(upstream, "_api", api), mock.patch.object(upstream, "_fetch", fetch): + with mock.patch.object(upstream, "cached_api", api), mock.patch.object(upstream, "fetch_body", fetch): found = history.find_revision( repo, "dists/engine-data/queen.tbl", hashlib.md5(b"pinned").hexdigest(), "unused") diff --git a/tests/test_foreign_tree.py b/tests/test_foreign_tree.py index 73a4810c0..2f19337a2 100644 --- a/tests/test_foreign_tree.py +++ b/tests/test_foreign_tree.py @@ -107,10 +107,10 @@ class AReleaseNamedAfterTheTree(unittest.TestCase): def test_only_whole_leading_words_name_the_tree(self): """dolphin-mmjr2 is not a release of dolphin-mmjr: mmjr2 is one word.""" - from resolve.ownership import _owner_tokens + from resolve.ownership import owner_tokens - self.assertNotIn("dolphinmmjr", _owner_tokens({"source_profile": "dolphin-mmjr2"})) - self.assertIn("cxbxreloaded", _owner_tokens({"source_profile": "cxbx-reloaded-2023"})) + self.assertNotIn("dolphinmmjr", owner_tokens({"source_profile": "dolphin-mmjr2"})) + self.assertIn("cxbxreloaded", owner_tokens({"source_profile": "cxbx-reloaded-2023"})) class AnotherMachinesRomIsNotServed(unittest.TestCase): diff --git a/tests/test_game_data_homonyms.py b/tests/test_game_data_homonyms.py index d0557e7a3..d6a3aa217 100644 --- a/tests/test_game_data_homonyms.py +++ b/tests/test_game_data_homonyms.py @@ -224,7 +224,7 @@ class SecondPassKeepsIdentity(unittest.TestCase): """ def test_flag_and_hashes_reach_the_alternative_destination(self): - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras sha = "a" * 40 md5 = "b" * 32 @@ -247,7 +247,7 @@ class SecondPassKeepsIdentity(unittest.TestCase): {"name": "pak1.pk3", "path": "maintt/pak1.pk3", "sha1": "c" * 40}, ], }} - extras = {e["destination"]: e for e in _collect_emulator_extras( + extras = {e["destination"]: e for e in collect_emulator_extras( config, "emulators", db, set(), "", profiles)} # Unsourceable is settled, as in the first pass: no copy at all. self.assertNotIn("mainta/pak1.pk3", extras) diff --git a/tests/test_hashing.py b/tests/test_hashing.py index 32cb47729..d4d6950d8 100644 --- a/tests/test_hashing.py +++ b/tests/test_hashing.py @@ -93,8 +93,8 @@ class TheSiteReadsAHashFieldTheResolversWay(unittest.TestCase): ("0xDEADBEEF", ["deadbeef"]), (12345678, ["12345678"]), ): with self.subTest(raw=raw): - self.assertEqual(lookup._hash_values(raw), expected) - self.assertEqual(lookup._hash_values(raw), sorted(hashing.parse_hash_list(raw))) + self.assertEqual(lookup.sorted_hash_values(raw), expected) + self.assertEqual(lookup.sorted_hash_values(raw), sorted(hashing.parse_hash_list(raw))) if __name__ == "__main__": diff --git a/tests/test_hidden_extras.py b/tests/test_hidden_extras.py index 87d52b4df..8b8c5d105 100644 --- a/tests/test_hidden_extras.py +++ b/tests/test_hidden_extras.py @@ -193,7 +193,7 @@ class TheReplayResolvesAsTheBuilder(unittest.TestCase): ) placed: set[str] = set() - with mock.patch.object(packextras, "_collect_emulator_extras", return_value=extras): + with mock.patch.object(packextras, "collect_emulator_extras", return_value=extras): hidden = packextras.hidden_extras( {"systems": {}}, "emulators", {"files": {}}, {}, {}, placed=placed, resolver=Resolver(), diff --git a/tests/test_install_cores.py b/tests/test_install_cores.py index bd98bf51b..ecd57bbb3 100644 --- a/tests/test_install_cores.py +++ b/tests/test_install_cores.py @@ -369,11 +369,11 @@ class APlatformOmissionKeepsItsClaim(unittest.TestCase): from packs import manifestentry held = {"cores": None} - self.assertTrue(manifestentry._claim_platform_omission(held, "melonds")) - self.assertTrue(manifestentry._claim_platform_omission(held, "melonds")) + self.assertTrue(manifestentry.claim_platform_omission(held, "melonds")) + self.assertTrue(manifestentry.claim_platform_omission(held, "melonds")) self.assertEqual(held["alternatives"], [{"cores": ["melonds"]}]) - self.assertFalse(manifestentry._claim_platform_omission({"cores": ["x"]}, "melonds")) - self.assertFalse(manifestentry._claim_platform_omission(None, "melonds")) + self.assertFalse(manifestentry.claim_platform_omission({"cores": ["x"]}, "melonds")) + self.assertFalse(manifestentry.claim_platform_omission(None, "melonds")) def test_the_boundary_takes_only_core_names(self): manifest = {"manifest_version": 2, "platform": "retroarch", "files": [], diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index c3849750b..1648ce75d 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -1053,7 +1053,7 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): def setUp(self): from model import profiles from model.platforms import _platform_config_cache - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache import generate_db tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) @@ -1096,9 +1096,9 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): "required": True}, ]})) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.addCleanup(_platform_config_cache.clear) - self.addCleanup(_emulator_profiles_cache.clear) + self.addCleanup(emulator_profiles_cache.clear) self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): @@ -1134,7 +1134,7 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): def setUp(self): from model import profiles from model.platforms import _platform_config_cache - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache import generate_db tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) @@ -1179,9 +1179,9 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): for name in ("eu.bin", "jp.bin") ]})) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.addCleanup(_platform_config_cache.clear) - self.addCleanup(_emulator_profiles_cache.clear) + self.addCleanup(emulator_profiles_cache.clear) self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): @@ -1217,7 +1217,7 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): def setUp(self): from model import profiles from model.platforms import _platform_config_cache - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache import generate_db tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) @@ -1268,9 +1268,9 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): {"name": "us.bin", "path": "alt/us.bin", "system": "sys", "required": False}, ]})) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.addCleanup(_platform_config_cache.clear) - self.addCleanup(_emulator_profiles_cache.clear) + self.addCleanup(emulator_profiles_cache.clear) self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index 3850fa403..e82aeb77d 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -30,7 +30,7 @@ import yaml import verify from packs import coverage from packs import report as packs_report -from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.profiles import emulator_profiles_cache, load_emulator_profiles from model.platforms import load_platform_config from cross_reference import LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, print_launcher_reads from packs.crossref import launcher_file_names, launcher_reads_not_held @@ -82,7 +82,7 @@ LAUNCHERS = [ class LauncherGapTest(unittest.TestCase): def setUp(self) -> None: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.root = tempfile.mkdtemp() self.bios_dir = os.path.join(self.root, "bios") self.platforms_dir = os.path.join(self.root, "platforms") diff --git a/tests/test_launcher_layer.py b/tests/test_launcher_layer.py index 240660858..b17358b3b 100644 --- a/tests/test_launcher_layer.py +++ b/tests/test_launcher_layer.py @@ -21,7 +21,7 @@ import zipfile import yaml -from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.profiles import emulator_profiles_cache, load_emulator_profiles from model.platforms import load_platform_config from resolve.launchers import LauncherLayer, launcher_places, suffixed_stem from packs.gaps import find_undeclared_files @@ -41,7 +41,7 @@ def _md5(data: bytes) -> str: class LauncherLayerTest(unittest.TestCase): def setUp(self) -> None: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.root = tempfile.mkdtemp() self.bios_dir = os.path.join(self.root, "bios") self.platforms_dir = os.path.join(self.root, "platforms") @@ -198,7 +198,7 @@ class LauncherLayerTest(unittest.TestCase): } with open(os.path.join(self.emulators_dir, "fixemu.yml"), "w") as fh: yaml.dump(profile, fh) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(self.emulators_dir) added = [u["path"] for u in self._report() if u.get("launcher")] self.assertNotIn("sub/fix.bin", added) @@ -226,7 +226,7 @@ class LauncherLayerTest(unittest.TestCase): yaml.dump(profile, fh) self.config["launchers"][2]["names"] = ["v103.bin"] self.config["launchers"][2]["search_dir"] = "/userdata/bios" - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(self.emulators_dir) report = {u["path"]: u for u in self._report()} self.assertNotIn("flash.bin", report) @@ -247,7 +247,7 @@ class LauncherLayerTest(unittest.TestCase): with open(os.path.join(self.emulators_dir, "fixemu.yml"), "w") as fh: yaml.dump(profile, fh) self.config["launchers"][2]["names"] = ["plain.bin"] - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(self.emulators_dir) self.assertNotIn("core.bin", {u["name"] for u in self._report()}) self.assertNotIn("core.bin", self._pack_names()) @@ -266,7 +266,7 @@ class LauncherLayerTest(unittest.TestCase): yaml.dump(profile, fh) self.config["launchers"][2]["names"] = ["launcher.rom"] self.config["launchers"][2]["passes_to"] = "command line -romslot" - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(self.emulators_dir) added = {u["path"]: u for u in self._report() if u.get("launcher")} self.assertEqual(added["launcher.rom"]["launcher_of"], "core.bin") @@ -283,7 +283,7 @@ class LauncherLayerTest(unittest.TestCase): with open(os.path.join(self.emulators_dir, "fixemu.yml"), "w") as fh: yaml.dump(profile, fh) self.config["launchers"][2]["names"] = ["kick.A500.rom"] - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(self.emulators_dir) added = {u["path"]: u for u in self._report() if u.get("launcher")} self.assertEqual(added["kick.A500.rom"]["md5"], _md5(CONTENT["core.bin"])) @@ -302,7 +302,7 @@ class LauncherLayerTest(unittest.TestCase): self.config["systems"]["test-sys"]["files"].append( {"name": "core.bin", "destination": "core.bin", "required": True} ) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(self.emulators_dir) added = {u["path"]: u for u in self._report() if u.get("launcher")} self.assertEqual(added["kick.A500.rom"]["md5"], _md5(CONTENT["core.bin"])) @@ -353,7 +353,7 @@ class LauncherLayerTest(unittest.TestCase): "overrides": [], "source_ref": "core-options.cfg:515", }) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(self.emulators_dir) added = {u["path"]: u for u in self._report() if u.get("launcher")} self.assertEqual(added["ps2/bios/scph10000.bin"]["md5"], _md5(older)) @@ -460,7 +460,7 @@ class LauncherLayerTest(unittest.TestCase): self.assertIn("LauncherLayer(", inspect.getsource(packs_gaps.find_undeclared_files)) self.assertIn(".settle(", inspect.getsource(packs_gaps.find_undeclared_files)) self.assertIn( - "undeclared_report(", inspect.getsource(packextras._collect_emulator_extras) + "undeclared_report(", inspect.getsource(packextras.collect_emulator_extras) ) self.assertIn( "find_undeclared_files(", inspect.getsource(packextras.undeclared_report) diff --git a/tests/test_launcher_placement.py b/tests/test_launcher_placement.py index 77d1aa38f..53d400c6f 100644 --- a/tests/test_launcher_placement.py +++ b/tests/test_launcher_placement.py @@ -23,7 +23,7 @@ from pathlib import Path import yaml -from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.profiles import emulator_profiles_cache, load_emulator_profiles from model.platforms import load_platform_config from resolve.standalone import platform_layouts, standalone_set from packs.manifest import generate_manifest @@ -46,7 +46,7 @@ LINK = { class ALinkMovesTheDestination(unittest.TestCase): def setUp(self) -> None: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, self.root, True) @@ -161,7 +161,7 @@ class ALinkMovesTheDestination(unittest.TestCase): "systems": ["commodore-amiga"], "files": [{"name": "kick.rom", "path": "kick.rom", "required": False}], })) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() manifest = self.manifest("linkplat") (held,) = [f for f in manifest["files"] if f["dest"] == "kick.rom"] self.assertEqual(held["cores"], ["other"]) @@ -175,7 +175,7 @@ class ALinkMovesTheDestination(unittest.TestCase): for key in ("kick-1", "kick-2"): (self.emulators / f"{key}.yml").write_text( yaml.safe_dump({**data, "built_by": ["linkplat"]})) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() omitted = [o for o in self.manifest("linkplat")["omitted_files"] if o["name"] == "kick.rom"] self.assertEqual([(o["root"], o["cores"]) for o in omitted], @@ -305,7 +305,7 @@ class AProgramRunFromItsFolder(unittest.TestCase): """ def setUp(self) -> None: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, self.root, True) @@ -572,7 +572,7 @@ class ASettingSetsTheBiosFolder(unittest.TestCase): """ def setUp(self) -> None: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, self.root, True) diff --git a/tests/test_libretro_layout.py b/tests/test_libretro_layout.py index ff11d1f1a..effc32ef9 100644 --- a/tests/test_libretro_layout.py +++ b/tests/test_libretro_layout.py @@ -15,7 +15,7 @@ import os import unittest from pathlib import Path -from packs.paths import _resolve_destination +from packs.paths import resolve_destination from resolve.validation import outside_gap_scope, read_from_save_dir, read_from_system_dir REPO_ROOT = Path(__file__).resolve().parents[1] @@ -24,11 +24,11 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class PathIsTheDestination(unittest.TestCase): def test_no_prefix_on_a_file(self): entry = {"name": "ppge_atlas.zim", "path": "PPSSPP/ppge_atlas.zim"} - self.assertEqual(_resolve_destination(entry, False), "PPSSPP/ppge_atlas.zim") + self.assertEqual(resolve_destination(entry, False), "PPSSPP/ppge_atlas.zim") dual = {"name": "IPL.bin", "path": "dolphin-emu/Sys/GC/USA/IPL.bin", "standalone_path": "GC/USA/IPL.bin"} - self.assertEqual(_resolve_destination(dual, False), "dolphin-emu/Sys/GC/USA/IPL.bin") - self.assertEqual(_resolve_destination(dual, True), "GC/USA/IPL.bin") + self.assertEqual(resolve_destination(dual, False), "dolphin-emu/Sys/GC/USA/IPL.bin") + self.assertEqual(resolve_destination(dual, True), "GC/USA/IPL.bin") class LoadFromPerBuild(unittest.TestCase): @@ -63,10 +63,10 @@ class RetroArchCarriesDolphinWhereItReads(unittest.TestCase): from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras config = load_platform_config("retroarch") - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, "emulators", load_database("database.json"), set(), config.get("base_destination", ""), load_emulator_profiles("emulators"), ) diff --git a/tests/test_maker_folder_names.py b/tests/test_maker_folder_names.py index 8655b80a2..3c28df216 100644 --- a/tests/test_maker_folder_names.py +++ b/tests/test_maker_folder_names.py @@ -29,7 +29,7 @@ from model import cliargs, platforms from resolve import cores, grouping, localfile from model.database import load_database from model.platforms import _platform_config_cache -from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.profiles import emulator_profiles_cache, load_emulator_profiles from model.registry import list_registered_platforms, load_data_dir_registry from resolve.localfile import resolve_local_file from resolve.ownership import BUCKET_FOLDERS, names_manufacturer @@ -104,13 +104,13 @@ class _Collection(unittest.TestCase): ) self.db = load_database("database.json") _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.config = platforms.load_platform_config("handheld", "platforms") self.profiles = load_emulator_profiles("emulators") def tearDown(self): _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() os.chdir(self._cwd) self._tmp.cleanup() diff --git a/tests/test_mame_devices.py b/tests/test_mame_devices.py index 9ff399d26..89173edd3 100644 --- a/tests/test_mame_devices.py +++ b/tests/test_mame_devices.py @@ -626,7 +626,7 @@ class APickReadsTheEntrySystems(unittest.TestCase): self.assertTrue(entry_serves_systems({}, profile, ["snk-neogeo-mvs"])) def test_the_gap_report_and_the_extras_carry_them(self): - from packs.extras import _collect_emulator_extras, _extra_system_ids + from packs.extras import collect_emulator_extras, extra_system_ids from packs.gaps import find_undeclared_files profile = { @@ -643,10 +643,10 @@ class APickReadsTheEntrySystems(unittest.TestCase): } (gap,) = find_undeclared_files(config, "emulators", db, emu_profiles={"mame": profile}) self.assertEqual(gap["systems"], ["apple2gs", "coco"]) - (extra,) = _collect_emulator_extras( + (extra,) = collect_emulator_extras( config, "emulators", db, set(), "", {"mame": profile}, include_all=True ) - self.assertEqual(_extra_system_ids(extra), ["apple2gs", "coco"]) + self.assertEqual(extra_system_ids(extra), ["apple2gs", "coco"]) def test_the_schema_and_the_profile_list(self): try: diff --git a/tests/test_manifest_entry.py b/tests/test_manifest_entry.py index 1fbf71d19..ad9f1994b 100644 --- a/tests/test_manifest_entry.py +++ b/tests/test_manifest_entry.py @@ -66,7 +66,7 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase): omitted[full_dest] = reason with mock.patch.object(manifestentry, "compute_hashes", return_value=hashes): - manifestcores._manifest_core_entries( + manifestcores.manifest_core_entries( [extra], {}, self.db, str(REPO_ROOT / "bios"), "", str(REPO_ROOT), {}, True, region_drops=set(), case_insensitive=False, seen_destinations=set(), diff --git a/tests/test_md5_pack_context.py b/tests/test_md5_pack_context.py index 2392a415a..99ccb5e8f 100644 --- a/tests/test_md5_pack_context.py +++ b/tests/test_md5_pack_context.py @@ -75,7 +75,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): import yaml - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache import generate_db from packs import emulatorpack @@ -99,7 +99,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): "systems": ["sega-triforce"], "files": [{"name": "segaboot.gcm", "required": True}], })) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() try: emulator_pack = emulatorpack.generate_emulator_pack( ["triforce"], str(root / "emulators"), db, str(root / "bios"), @@ -110,7 +110,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): str(root / "bios"), str(out), offline=True, ) finally: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.assertNotEqual(Path(emulator_pack).name, Path(system_pack).name) self.assertTrue(Path(emulator_pack).exists()) self.assertTrue(Path(system_pack).exists()) diff --git a/tests/test_minui_platform.py b/tests/test_minui_platform.py index e8f8c4359..fbd7991a0 100644 --- a/tests/test_minui_platform.py +++ b/tests/test_minui_platform.py @@ -169,9 +169,9 @@ class PackPlacesCoreFilesUnderTheTag(unittest.TestCase): folder the platform hands it, and nowhere else.""" def setUp(self): - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.root = tempfile.mkdtemp(dir=REPO_ROOT / "tmp" / "tests") self.bios = os.path.join(self.root, "bios") self.platforms = os.path.join(self.root, "platforms") diff --git a/tests/test_native_mode.py b/tests/test_native_mode.py index 7d27fa1ca..9b15108dd 100644 --- a/tests/test_native_mode.py +++ b/tests/test_native_mode.py @@ -221,12 +221,12 @@ class GapAnalysisAgreesWithTheBuilder(unittest.TestCase): return tmp, root, db def _in_repo(self, mode: str) -> bool: - from model.profiles import _emulator_profiles_cache, load_emulator_profiles + from model.profiles import emulator_profiles_cache, load_emulator_profiles from packs.gaps import find_undeclared_files tmp, root, db = self._fixture() try: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(str(root / "emulators")) config = { "platform": "Demo", @@ -240,7 +240,7 @@ class GapAnalysisAgreesWithTheBuilder(unittest.TestCase): entry = next(e for e in found if e["name"] == "collide.rom") return bool(entry["in_repo"]) finally: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() tmp.cleanup() def test_a_digest_mode_does_not_call_a_contradicted_copy_available(self): @@ -367,7 +367,7 @@ class SkippingIsNotSettling(unittest.TestCase): import hashlib import tempfile - from model.profiles import _emulator_profiles_cache, load_emulator_profiles + from model.profiles import emulator_profiles_cache, load_emulator_profiles from packs.gaps import find_undeclared_files tmp = tempfile.TemporaryDirectory() @@ -398,7 +398,7 @@ class SkippingIsNotSettling(unittest.TestCase): "files:\n" + entry ) try: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = load_emulator_profiles(str(root / "emulators")) config = { "platform": "Demo", "verification_mode": "existence", @@ -409,7 +409,7 @@ class SkippingIsNotSettling(unittest.TestCase): ) return {(u["emulator"], u["name"]) for u in found} finally: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() tmp.cleanup() def test_the_profile_that_needs_the_file_still_reports_it(self): diff --git a/tests/test_no_game_data.py b/tests/test_no_game_data.py index fb1e67335..a97eee9a5 100644 --- a/tests/test_no_game_data.py +++ b/tests/test_no_game_data.py @@ -29,7 +29,7 @@ from pathlib import Path import yaml from model.platforms import load_platform_config, _platform_config_cache -from model.profiles import _emulator_profiles_cache +from model.profiles import emulator_profiles_cache import generate_db from packs import archive as packs_archive from packs import manifest as packs_manifest @@ -107,13 +107,13 @@ class _Fixture(unittest.TestCase): yaml.dump({"platforms": {"handheld": {"config": "handheld.yml"}}}) ) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.out = self.root / "dist" self.out.mkdir() def tearDown(self): _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def pack(self, no_game_data: bool) -> tuple[str, set[str], str]: diff --git a/tests/test_pack_conformance_dirs.py b/tests/test_pack_conformance_dirs.py index e7aa67025..523cc1ab6 100644 --- a/tests/test_pack_conformance_dirs.py +++ b/tests/test_pack_conformance_dirs.py @@ -64,10 +64,10 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase): with mock.patch.object(packs_finalize, "list_registered_platforms", return_value=["fix"]), \ mock.patch.object( - packs_finalize, "_expected_pack_names", + packs_finalize, "expected_pack_names", return_value={"fix": {"Fix_BIOS_Pack.zip"}}, ), \ - mock.patch.object(packs_finalize, "_pack_archives", return_value=["Fix_BIOS_Pack.zip"]), \ + mock.patch.object(packs_finalize, "pack_archives", return_value=["Fix_BIOS_Pack.zip"]), \ mock.patch.object( packs_finalize, "verify_pack", return_value=(True, {"summary": { diff --git a/tests/test_pack_core_extras.py b/tests/test_pack_core_extras.py index 2f17fc8eb..6c01f9ad7 100644 --- a/tests/test_pack_core_extras.py +++ b/tests/test_pack_core_extras.py @@ -150,7 +150,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): def setUp(self): from model.platforms import _platform_config_cache - from model.profiles import load_emulator_profiles, _emulator_profiles_cache + from model.profiles import load_emulator_profiles, emulator_profiles_cache import generate_db tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) @@ -185,9 +185,9 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): {"name": "extra.bin", "path": "extra.bin", "required": False}, ]}), encoding="utf-8") _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.addCleanup(_platform_config_cache.clear) - self.addCleanup(_emulator_profiles_cache.clear) + self.addCleanup(emulator_profiles_cache.clear) self.profiles = load_emulator_profiles("emulators") def _build(self, source: str, required: bool) -> tuple[str, set[str]]: @@ -221,7 +221,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): ok, _c, _p, errors, *_rest = self._check(zip_path, source, required) self.assertTrue(ok, errors) self.assertEqual( - naming._pack_variant(os.path.basename(zip_path)), (source, required) + naming.pack_variant(os.path.basename(zip_path)), (source, required) ) def test_a_narrowed_pack_missing_a_required_file_fails(self): diff --git a/tests/test_pack_counts.py b/tests/test_pack_counts.py index 9190cede4..43554be71 100644 --- a/tests/test_pack_counts.py +++ b/tests/test_pack_counts.py @@ -30,7 +30,7 @@ except ImportError: jsonschema = None from core.artifacts import ArtifactLockBusy, artifact_lock from model.platforms import _platform_config_cache -from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.profiles import emulator_profiles_cache, load_emulator_profiles import generate_db from packs import archive as packs_archive from packs import datatrees @@ -111,11 +111,11 @@ class PackCountFixture(unittest.TestCase): yaml.dump({"platforms": {"demo": {"config": "demo.yml"}}}) ) (self.emulators / "demo.yml").write_text(PROFILE) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self.profiles = load_emulator_profiles(str(self.emulators)) def tearDown(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def _manifest(self) -> dict: @@ -656,7 +656,7 @@ class CoreCopiesKeepTheirCategory(unittest.TestCase): copies, game data, under core files.""" def test_a_copy_counts_as_its_entry_says(self): - from packs.extras import _collect_emulator_extras, hidden_extras + from packs.extras import collect_emulator_extras, hidden_extras with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: held = Path(tmp) / "x.dat" @@ -672,7 +672,7 @@ class CoreCopiesKeepTheirCategory(unittest.TestCase): }} db = {"files": {sha1: {"path": str(held), "name": "x.dat", "sha1": sha1}}, "indexes": {"by_name": {"x.dat": [sha1]}, "by_path_suffix": {}}} - (extra,) = _collect_emulator_extras( + (extra,) = collect_emulator_extras( config, "emulators", db, {"x.dat"}, "", profiles ) self.assertEqual( diff --git a/tests/test_pack_destinations.py b/tests/test_pack_destinations.py index 3bcd57c53..4e9f9d6da 100644 --- a/tests/test_pack_destinations.py +++ b/tests/test_pack_destinations.py @@ -29,9 +29,9 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class _Fixture(unittest.TestCase): def setUp(self) -> None: - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, self.root, True) @@ -175,9 +175,9 @@ class EveryNarrowingIsCompared(unittest.TestCase): import inspect import pipeline - from packs.naming import _narrowings + from packs.naming import pack_narrowings - dimensions = set(inspect.signature(_narrowings).parameters) + dimensions = set(inspect.signature(pack_narrowings).parameters) compared = set(pipeline.NARROWINGS_COMPARED) exempt = set(pipeline.NARROWINGS_NOT_COMPARED) self.assertFalse(compared & exempt) @@ -192,10 +192,10 @@ class EveryNarrowingIsCompared(unittest.TestCase): import inspect import pipeline - from packs.naming import _narrowings + from packs.naming import pack_narrowings from packs.emulatorpack import generate_emulator_pack - taken = (set(inspect.signature(_narrowings).parameters) + taken = (set(inspect.signature(pack_narrowings).parameters) & set(inspect.signature(generate_emulator_pack).parameters)) self.assertEqual(taken, set(pipeline.EMULATOR_NARROWINGS_COMPARED)) profile = {"files": [{"name": "a.bin", "region": "japan"}, diff --git a/tests/test_pack_file_names.py b/tests/test_pack_file_names.py index 9b0a8e0c9..c64180b1c 100644 --- a/tests/test_pack_file_names.py +++ b/tests/test_pack_file_names.py @@ -15,7 +15,7 @@ import tempfile import unittest from pathlib import Path -from packs.naming import _name_part +from packs.naming import file_name_part from packs.emulatorpack import generate_emulator_pack REPO_ROOT = Path(__file__).resolve().parent.parent @@ -23,8 +23,8 @@ REPO_ROOT = Path(__file__).resolve().parent.parent class PackFileNames(unittest.TestCase): def test_separators_and_reserved_characters_are_replaced(self): - self.assertEqual(_name_part("FinalBurn Neo (CPS-1/CPS-2)"), "FinalBurnNeo(CPS-1-CPS-2)") - self.assertEqual(_name_part('a\\b:c*d?"eg|h', "_"), "a-b-c-d--e-f-g-h") + self.assertEqual(file_name_part("FinalBurn Neo (CPS-1/CPS-2)"), "FinalBurnNeo(CPS-1-CPS-2)") + self.assertEqual(file_name_part('a\\b:c*d?"eg|h', "_"), "a-b-c-d--e-f-g-h") def test_an_emulator_named_with_a_slash_writes_its_pack(self): with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: diff --git a/tests/test_pack_integrity.py b/tests/test_pack_integrity.py index ecc512145..809809957 100644 --- a/tests/test_pack_integrity.py +++ b/tests/test_pack_integrity.py @@ -32,9 +32,9 @@ def _pack_path(platform_name: str) -> str | None: """Path of the platform's full pack, by the exact name the builder writes.""" if not os.path.isdir(DIST_DIR): return None - from packs.naming import _expected_pack_names + from packs.naming import expected_pack_names - names = _expected_pack_names([platform_name], PLATFORMS_DIR, [], None) + names = expected_pack_names([platform_name], PLATFORMS_DIR, [], None) for entry in sorted(names[platform_name]): path = os.path.join(DIST_DIR, entry) if os.path.isfile(path): diff --git a/tests/test_pack_readme.py b/tests/test_pack_readme.py index d5d8bd218..4283ec376 100644 --- a/tests/test_pack_readme.py +++ b/tests/test_pack_readme.py @@ -16,7 +16,7 @@ from pathlib import Path import yaml -from packs.readme import _build_readme +from packs.readme import build_readme REPO_ROOT = Path(__file__).resolve().parents[1] @@ -27,7 +27,7 @@ def _extract_lines(text: str) -> list[str]: class GuidesPointAtTheReadPath(unittest.TestCase): def test_retrodeck_is_extracted_at_its_root(self): - text = _build_readme("retrodeck", "RetroDECK", "", 1, 1) + text = build_readme("retrodeck", "RetroDECK", "", 1, 1) for line in _extract_lines(text): self.assertNotIn("retrodeck/bios", line) @@ -37,7 +37,7 @@ class GuidesPointAtTheReadPath(unittest.TestCase): detect = (data.get("install", {}) or {}).get("detect", []) if not any(d.get("bios_path") for d in detect): continue - text = _build_readme(name, name, "", 1, 1, detect=detect) + text = build_readme(name, name, "", 1, 1, detect=detect) with self.subTest(platform=name): self.assertFalse( any("your BIOS directory" in line for line in _extract_lines(text)) @@ -51,7 +51,7 @@ class ACardOpenedOnAComputerShowsItsShareDrive(unittest.TestCase): def test_the_card_steps_name_the_drive_folder(self): for name in ("batocera", "recalbox"): - text = _build_readme(name, name, "", 1, 1) + text = build_readme(name, name, "", 1, 1) card = text[text.index("Manual (SD card)"):] card = card[:card.index("\n\n", card.index("1."))] with self.subTest(platform=name): @@ -74,7 +74,7 @@ def _registry() -> dict: def _guide(name: str) -> str: install = _registry()["platforms"][name].get("install") or {} - return _build_readme(name, name, "", 1, 1, detect=install.get("detect", []), + return build_readme(name, name, "", 1, 1, detect=install.get("detect", []), standalone_copies=install.get("standalone_copies", [])) @@ -136,7 +136,7 @@ class GuidesInstallFromTheZipInHand(unittest.TestCase): detect = (data.get("install", {}) or {}).get("detect", []) if not detect: continue - text = _build_readme(name, name, "", 1, 1, detect=detect) + text = build_readme(name, name, "", 1, 1, detect=detect) if "Option A: Automatic" not in text: continue with self.subTest(platform=name): diff --git a/tests/test_path_conflict_status.py b/tests/test_path_conflict_status.py index 04ba371fe..564b8ea8f 100644 --- a/tests/test_path_conflict_status.py +++ b/tests/test_path_conflict_status.py @@ -21,7 +21,7 @@ from pathlib import Path import yaml from model.platforms import load_platform_config, _platform_config_cache -from model.profiles import _emulator_profiles_cache +from model.profiles import emulator_profiles_cache import generate_db from packs import emulatorpack from packs import platformpack @@ -69,7 +69,7 @@ class ConflictingDeclarations(unittest.TestCase): yaml.dump({"platforms": {"conflict": {"config": "conflict.yml"}}}) ) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): _platform_config_cache.clear() @@ -145,11 +145,11 @@ class AnExtraDoesNotPassAHashCheck(unittest.TestCase): } (self.emulators / "fxcore.yml").write_text(yaml.dump(profile)) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def test_the_declaration_stays_failed(self): @@ -198,10 +198,10 @@ class TheEmulatorPackShipsWhatTheCoreAccepts(unittest.TestCase): "max_size": 1048576, "validation": ["size"]}], } (self.emulators / "mac.yml").write_text(yaml.dump(profile)) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def test_the_refused_rom_is_named_not_shipped(self): @@ -256,10 +256,10 @@ class AlternativesAgreeWithThePack(unittest.TestCase): ], } (self.emulators / "eng.yml").write_text(yaml.dump(profile)) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def test_verify_counts_what_the_pack_ships(self): @@ -319,10 +319,10 @@ class AMaskedArchiveIsMissing(unittest.TestCase): "files": [{"name": "y.bin", "archive": "pack.zip", "required": True, "crc32": f"{__import__('zlib').crc32(b'y'):08x}"}], })) - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() self._tmp.cleanup() def test_both_report_the_archive_missing(self): diff --git a/tests/test_path_null_copies.py b/tests/test_path_null_copies.py index 8686c612a..0ca2d116a 100644 --- a/tests/test_path_null_copies.py +++ b/tests/test_path_null_copies.py @@ -27,7 +27,7 @@ class NoPathNoCopy(unittest.TestCase): from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packs.extras import _collect_emulator_extras + from packs.extras import collect_emulator_extras profiles = load_emulator_profiles("emulators") nameless = { @@ -36,7 +36,7 @@ class NoPathNoCopy(unittest.TestCase): if isinstance(f, dict) and "path" in f and f["path"] is None } config = load_platform_config("retroarch") - extras = _collect_emulator_extras( + extras = collect_emulator_extras( config, "emulators", load_database("database.json"), set(), config.get("base_destination", ""), profiles, ) diff --git a/tests/test_profile_checks.py b/tests/test_profile_checks.py index 22615d913..15255e77a 100644 --- a/tests/test_profile_checks.py +++ b/tests/test_profile_checks.py @@ -18,7 +18,7 @@ from pathlib import Path import yaml -from resolve.validation import _build_validation_index, check_file_validation +from resolve.validation import build_validation_index, check_file_validation REPO_ROOT = Path(__file__).resolve().parents[1] @@ -37,7 +37,7 @@ class _Probe(unittest.TestCase): def accepts(self, emulator: str, name: str, data: bytes, strict: bool = False) -> bool: """strict counts a check the code only warns about.""" - index = _build_validation_index({emulator: _profile(emulator)}) + index = build_validation_index({emulator: _profile(emulator)}) path = Path(self._tmp.name) / name path.write_bytes(data) return check_file_validation( diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index 535f076c9..6f7f55e81 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -859,7 +859,7 @@ class TestSymlinkTarget(unittest.TestCase): class TestAnchorTokens(unittest.TestCase): def test_archive_members_supply_the_content_values(self): - tokens = profiling_citations._anchor_tokens( + tokens = profiling_citations.anchor_tokens( {"name": "esh.zip", "contents": [{"crc32": "c14f36b3"}]} ) # The set name stays: a MAME ref cites the machine declaration, which @@ -867,24 +867,24 @@ class TestAnchorTokens(unittest.TestCase): self.assertEqual(tokens, ["c14f36b3", "esh"]) def test_a_hashless_archive_still_falls_back_to_its_stem(self): - tokens = profiling_citations._anchor_tokens( + tokens = profiling_citations.anchor_tokens( {"name": "esh.zip", "contents": [{"name": "rom.u1"}]} ) self.assertIn("esh", tokens) def test_archive_stem_is_searched_too(self): - tokens = profiling_citations._anchor_tokens({"name": "stvbios.zip"}) + tokens = profiling_citations.anchor_tokens({"name": "stvbios.zip"}) self.assertIn("stvbios.zip", tokens) self.assertIn("stvbios", tokens) def test_hashes_still_win(self): - tokens = profiling_citations._anchor_tokens( + tokens = profiling_citations.anchor_tokens( {"name": "a.zip", "sha1": "AABB" * 10} ) self.assertIn("aabb" * 10, tokens) def test_very_short_stem_is_skipped(self): - self.assertNotIn("ab", profiling_citations._anchor_tokens({"name": "ab.zip"})) + self.assertNotIn("ab", profiling_citations.anchor_tokens({"name": "ab.zip"})) class TestNudgeToDeclared(unittest.TestCase): @@ -1285,8 +1285,8 @@ class TestBuildReport(unittest.TestCase): upstream.list_tags, upstream.resolve_tag_commit, upstream.tag_commit, - upstream._http_json, - upstream._http_text, + upstream.http_json, + upstream.http_text, upstream.list_gitlinks, upstream.current_slug, upstream.fork_base, @@ -1315,8 +1315,8 @@ class TestBuildReport(unittest.TestCase): def _no_network(url): raise AssertionError(f"test reached the network: {url}") - upstream._http_json = _no_network - upstream._http_text = _no_network + upstream.http_json = _no_network + upstream.http_text = _no_network upstream.list_tags = ( lambda repo, cache, offline=False: self.tags ) @@ -1356,8 +1356,8 @@ class TestBuildReport(unittest.TestCase): upstream.list_tags, upstream.resolve_tag_commit, upstream.tag_commit, - upstream._http_json, - upstream._http_text, + upstream.http_json, + upstream.http_text, upstream.list_gitlinks, upstream.current_slug, upstream.fork_base, @@ -2206,7 +2206,7 @@ class TestExtrasSurviveARefusingForge(unittest.TestCase): profiling_run._attach_detection(self._args(), self._profile(), report) buffer = io.StringIO() with contextlib.redirect_stdout(buffer): - detection._print_extras(self._args(), self._profile(), report) + detection.print_extras(self._args(), self._profile(), report) finally: upstream.fetch_file = original self.assertEqual(report.detection_skipped, "https://x/y: HTTP 403") @@ -2731,7 +2731,7 @@ class TestWriteDryRun(unittest.TestCase): with mock.patch.object(profiling_run, "_build_full_report", return_value=skipped), \ mock.patch.object(profiling_run, "realign_prose", side_effect=cold), \ contextlib.redirect_stderr(io.StringIO()) as err: - profiling_run._read_one( + profiling_run.read_one_profile( self._args(rebase_refs=True), "p", yaml.safe_load(SAMPLE), reports, failed, True ) self.assertEqual(reports, [skipped]) @@ -3145,7 +3145,7 @@ class TestDeliberatelyFrozenPin(TestBuildReport): class TestProseSpacingIsNotADifference(unittest.TestCase): """A recale keeps the author's spacing, so the check has to allow for it. - _run_after_moves renders `a.c:228,1439-1443` while the writer leaves the + run_after_moves renders `a.c:228,1439-1443` while the writer leaves the sentence as written, `a.c:228, 1439-1443`. Comparing the two literally made the run look unwritten, so bump_commit refused for ever: mariani was held back by three of them. @@ -3153,20 +3153,20 @@ class TestProseSpacingIsNotADifference(unittest.TestCase): def test_a_written_run_counts_as_written_whatever_the_spacing(self): self.assertEqual( - profiling_citations._citation_key("src/Harddisk.cpp:228, 1439-1443"), - profiling_citations._citation_key("src/Harddisk.cpp:228,1439-1443"), + profiling_citations.citation_key("src/Harddisk.cpp:228, 1439-1443"), + profiling_citations.citation_key("src/Harddisk.cpp:228,1439-1443"), ) def test_different_citations_still_differ(self): self.assertNotEqual( - profiling_citations._citation_key("a.c:1, 2"), - profiling_citations._citation_key("a.c:1, 3"), + profiling_citations.citation_key("a.c:1, 2"), + profiling_citations.citation_key("a.c:1, 3"), ) def test_a_path_change_still_differs(self): self.assertNotEqual( - profiling_citations._citation_key("a.c:1"), - profiling_citations._citation_key("src/a.c:1"), + profiling_citations.citation_key("a.c:1"), + profiling_citations.citation_key("src/a.c:1"), ) @@ -3660,7 +3660,7 @@ class APassedReleaseIsNewerThanTheTag(unittest.TestCase): args = argparse.Namespace(cache_dir="c", offline=True) with mock.patch.object(upstream, "tag_commit", return_value="rel20"), \ mock.patch.object(upstream, "ancestry", return_value=(5, 0)): - self.assertIsNone(versions._passed_release(args, "repo", version, "pin")) + self.assertIsNone(versions.latest_passed_release(args, "repo", version, "pin")) class ANewerReleaseThanTheTag(unittest.TestCase): @@ -3674,7 +3674,7 @@ class ANewerReleaseThanTheTag(unittest.TestCase): answers = iter([after_tag, after_pin]) with mock.patch.object(upstream, "tag_commit", return_value="rel29"), \ mock.patch.object(upstream, "ancestry", side_effect=lambda *a, **k: next(answers)): - return versions._newer_release(args, "repo", version, "tag28") + return versions.newer_release(args, "repo", version, "tag28") def test_a_later_release_is_named(self): self.assertEqual(self._newer((12, 0), (12, 0)), "2.9") @@ -3711,7 +3711,7 @@ class AProjectThatOnlyTags(unittest.TestCase): args = argparse.Namespace(cache_dir="c", offline=True) with mock.patch.object(upstream, "tag_commit", return_value="tag13"), \ mock.patch.object(upstream, "ancestry", return_value=(7, 0)): - self.assertEqual(versions._newer_release(args, "repo", version, "tag12"), "v1.3") + self.assertEqual(versions.newer_release(args, "repo", version, "tag12"), "v1.3") class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase): @@ -3736,7 +3736,7 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase): with self.subTest(declared=declared, release=release), \ mock.patch.object(upstream, "tag_commit", return_value="rel"), \ mock.patch.object(upstream, "ancestry", return_value=(3, 0)): - self.assertEqual(versions._passed_release(args, "repo", version, "pin"), expected) + self.assertEqual(versions.latest_passed_release(args, "repo", version, "pin"), expected) def test_no_tag_and_nothing_passed_stays_quiet(self): version = versions.VersionReport("9.0.5", None, None, None, False, None) @@ -3746,10 +3746,10 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase): class TestAncestry(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() - self.saved = upstream._http_json + self.saved = upstream.http_json def tearDown(self): - upstream._http_json = self.saved + upstream.http_json = self.saved self.tmp.cleanup() def test_github_answers_both_directions_at_once(self): @@ -3759,7 +3759,7 @@ class TestAncestry(unittest.TestCase): calls.append(url) return {"ahead_by": 3, "behind_by": 0} - upstream._http_json = answer + upstream.http_json = answer repo = upstream.parse_repo("https://github.com/o/n") self.assertEqual( upstream.ancestry(repo, "tag", "pin", self.tmp.name), (3, 0) @@ -3771,7 +3771,7 @@ class TestAncestry(unittest.TestCase): forward = "from=tag&to=pin" in url return {"commits": [{}] * (0 if forward else 5)} - upstream._http_json = answer + upstream.http_json = answer repo = upstream.parse_repo("https://gitlab.com/o/n") self.assertEqual( upstream.ancestry(repo, "tag", "pin", self.tmp.name), (0, 5) @@ -4205,7 +4205,7 @@ class TestCollectCitations(unittest.TestCase): def test_run_is_rendered_with_its_written_path(self): parts = [RefPart("mupen64plus-video-rice/upstream/src/Config.cpp", 38, 38, "38")] self.assertEqual( - proseedit._run_after_moves(parts, {0: (40, 40, None)}, "Config.cpp:38"), + proseedit.run_after_moves(parts, {0: (40, 40, None)}, "Config.cpp:38"), "Config.cpp:40", ) @@ -5160,15 +5160,15 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \ mock.patch("core.artifacts.write_if_changed") as written, \ contextlib.redirect_stderr(io.StringIO()): - profiling_run._WRITTEN.clear() + profiling_run.WRITTEN_PROFILES.clear() profile_sync._refresh_source_paths(self._args()) self.assertFalse(built.called) - profiling_run._WRITTEN.add("x") + profiling_run.WRITTEN_PROFILES.add("x") profile_sync._refresh_source_paths(self._args(dry_run=True)) self.assertFalse(built.called) profile_sync._refresh_source_paths(self._args()) self.assertTrue(built.called and written.called) - profiling_run._WRITTEN.clear() + profiling_run.WRITTEN_PROFILES.clear() def test_the_record_reads_the_pins_just_written(self): @@ -5177,14 +5177,14 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): from unittest import mock from model import profiles as model_profiles - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from sitegen import sources with tempfile.TemporaryDirectory() as tmp: profile = Path(tmp) / "p.yml" profile.write_text('emulator: P\nsource_commit: "old"\n', encoding="utf-8") - _emulator_profiles_cache.clear() - self.addCleanup(_emulator_profiles_cache.clear) + emulator_profiles_cache.clear() + self.addCleanup(emulator_profiles_cache.clear) model_profiles.load_emulator_profiles(tmp, skip_aliases=False) profile.write_text('emulator: P\nsource_commit: "new"\n', encoding="utf-8") with mock.patch.object(sources, "build_source_paths", return_value=({}, [])) as built, \ @@ -5192,8 +5192,8 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): mock.patch("core.artifacts.write_if_changed"), \ contextlib.redirect_stderr(io.StringIO()), \ contextlib.redirect_stdout(io.StringIO()): - profiling_run._WRITTEN.add("p") - self.addCleanup(profiling_run._WRITTEN.clear) + profiling_run.WRITTEN_PROFILES.add("p") + self.addCleanup(profiling_run.WRITTEN_PROFILES.clear) profile_sync._refresh_source_paths(self._args(emulators_dir=tmp)) self.assertEqual(built.call_args[0][0]["p"]["source_commit"], "new") @@ -5901,7 +5901,7 @@ class ARecaleKeepsTheRepositoryWord(unittest.TestCase): part = sourceref.RefPart( profiling_citations.strip_repo_word(p.path, {"stella"}), p.start, p.end, p.raw) result = anchoring.PartResult(part, "SHIFTED", None, 140, 150, [], "") - self.assertEqual(profiling_reports._rendered_part(result), expected) + self.assertEqual(profiling_reports.rendered_part(result), expected) class EachCitationNamesTheCodeThatAsks(unittest.TestCase): @@ -6047,9 +6047,9 @@ class ARoleIsReadPerPart(unittest.TestCase): self.assertEqual(prose[0].parts[0].repo, "alek/x") def test_the_prose_grammar_keeps_the_role(self): - from model.sourceref import _prose_runs + from model.sourceref import prose_runs - runs = list(_prose_runs( + runs = list(prose_runs( "# ref: source src/a.cpp:1656-1685, 1709-1738, upstream b.c:5" )) roles = [(p.path, p.role) for run in runs for p in run[3]] @@ -6060,7 +6060,7 @@ class ARoleIsReadPerPart(unittest.TestCase): def test_an_abbreviated_location_reads_in_the_file_named_last(self): """devilutionx writes `Source/engine/assets.cpp:` then `(:507)` for each loader, and its pin moved under five uncollected numbers.""" - from model.sourceref import _prose_runs + from model.sourceref import prose_runs text = ( "Load order is defined in Source/engine/assets.cpp:\n" @@ -6071,7 +6071,7 @@ class ARoleIsReadPerPart(unittest.TestCase): ":44,65) and lightspark's (tools/errorgen:20).\n" ) cited = [ - (p.path, p.start, p.end) for run in _prose_runs(text) for p in run[3] + (p.path, p.start, p.end) for run in prose_runs(text) for p in run[3] ] self.assertEqual(cited, [ ("Source/engine/assets.cpp", 507, 507), @@ -6086,9 +6086,9 @@ class ARoleIsReadPerPart(unittest.TestCase): ]) def test_an_abbreviated_location_needs_a_file_before_it(self): - from model.sourceref import _prose_runs + from model.sourceref import prose_runs - self.assertEqual(list(_prose_runs("read at boot (:507), devilutionx.mpq")), []) + self.assertEqual(list(prose_runs("read at boot (:507), devilutionx.mpq")), []) class AnOnlinePassSaysWhereItIs(unittest.TestCase): @@ -6134,7 +6134,7 @@ class AnOnlinePassSaysWhereItIs(unittest.TestCase): err = io.StringIO() with mock.patch.object(triage.time, "monotonic", lambda: next(clock)), \ contextlib.redirect_stderr(err): - progress = triage._Progress(9, "read", quiet=False) + progress = triage.Progress(9, "read", quiet=False) for done, name in enumerate(("a", "b", "c")): progress.step(done, name) self.assertEqual(err.getvalue(), "read: 1 of 9, at b\n") @@ -6177,7 +6177,7 @@ class TheTriageCountsWhatBlocksThePin(unittest.TestCase): mock.patch.object(upstream, "commits_touching", return_value=0), \ contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - triage._print_triage(args, selected, reports) + triage.print_triage(args, selected, reports) lines = out.getvalue().splitlines() self.assertIn("profile", lines[0]) self.assertIn("stuck", lines[1]) @@ -6200,7 +6200,7 @@ class TheTriageCountsWhatBlocksThePin(unittest.TestCase): mock.patch.object(upstream, "commits_touching", return_value=0), \ contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - triage._print_triage(args, selected, reports) + triage.print_triage(args, selected, reports) lines = out.getvalue().splitlines() self.assertIn("gone", lines[1]) self.assertEqual(lines[-1], "2 profiles, 1 with something to review") diff --git a/tests/test_pypi_package.py b/tests/test_pypi_package.py index bf1198d51..34adfc218 100644 --- a/tests/test_pypi_package.py +++ b/tests/test_pypi_package.py @@ -151,13 +151,13 @@ class AnUnpinnedInstallerIsRefused(unittest.TestCase): root = Path(name) (root / "install.py").write_bytes(b"print('another')\n") shutil.copyfile(REPO_ROOT / "install.sh", root / "install.sh") - original = pypi.ROOT - pypi.ROOT = root + original = pypi.REPO_ROOT + pypi.REPO_ROOT = root try: with self.assertRaises(ValueError): pypi.installer_bytes() finally: - pypi.ROOT = original + pypi.REPO_ROOT = original def _python38() -> str | None: diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index 089d2285d..5faf62436 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -22,8 +22,8 @@ from unittest import mock import refresh_data_dirs as rdd from packs import datadirs -from model.registry import _load_versions -from packs.datatrees import _data_directory_members +from model.registry import load_versions +from packs.datatrees import data_directory_members REPO_ROOT = Path(__file__).resolve().parents[1] @@ -106,12 +106,12 @@ class RefreshConcurrency(unittest.TestCase): lambda *a, **k: _Response(payload)), \ mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"): self.assertTrue(datadirs.refresh_entry("pak", entry, versions_path=self.versions)) - self.assertEqual(_load_versions(self.versions)["pak"]["archive_size"], + self.assertEqual(load_versions(self.versions)["pak"]["archive_size"], len(payload)) datadirs._record_version("pak", {"sha": "e1"}, self.versions) (self.cache / "a.bin").write_bytes(b"kept") self.assertFalse(datadirs.refresh_entry("pak", entry, versions_path=self.versions)) - self.assertEqual(_load_versions(self.versions)["pak"], + self.assertEqual(load_versions(self.versions)["pak"], {"sha": "e1", "archive_size": len(payload)}) self.assertEqual((self.cache / "a.bin").read_bytes(), b"kept") @@ -188,7 +188,7 @@ class RefreshConcurrency(unittest.TestCase): thread.start() for thread in threads: thread.join() - self.assertEqual(sorted(_load_versions(self.versions)), sorted(keys)) + self.assertEqual(sorted(load_versions(self.versions)), sorted(keys)) class PackWalkHoldsTheCache(unittest.TestCase): @@ -203,7 +203,7 @@ class PackWalkHoldsTheCache(unittest.TestCase): (cache / "b.mkf").write_bytes(b"b") systems = {"s": {"data_directories": [{"ref": "sdlpal", "destination": "sdlpal"}]}} registry = {"sdlpal": {"local_cache": str(cache)}} - walk = _data_directory_members(systems, registry, "p", "", False, set(), set(), set()) + walk = data_directory_members(systems, registry, "p", "", False, set(), set(), set()) next(walk) with open(cache.with_name(".sdlpal.lock"), "a") as handle, self.assertRaises( BlockingIOError @@ -218,7 +218,7 @@ class EmulatorPackHoldsTheCache(unittest.TestCase): def test_the_walk_holds_a_shared_lock(self): import fcntl - from packs.datatrees import _pack_data_tree + from packs.datatrees import pack_data_tree with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: cache = Path(tmp) / "data" / "scummvm" @@ -236,8 +236,8 @@ class EmulatorPackHoldsTheCache(unittest.TestCase): fcntl.flock(handle, fcntl.LOCK_UN) held.append(False) - with mock.patch("packs.datatrees._add_pack_member", member): - _pack_data_tree(None, str(cache), "scummvm", set(), set(), set()) + with mock.patch("packs.datatrees.add_pack_member", member): + pack_data_tree(None, str(cache), "scummvm", set(), set(), set()) self.assertEqual(held, [True]) @@ -304,7 +304,7 @@ class TheManifestCarriesTheArchiveSize(unittest.TestCase): the installer announces as the tree's download.""" def test_recorded_size_is_written_and_an_unrecorded_one_left_out(self): - from packs.datatrees import _manifest_data_directories + from packs.datatrees import manifest_data_directories (REPO_ROOT / "tmp").mkdir(exist_ok=True) with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: @@ -319,7 +319,7 @@ class TheManifestCarriesTheArchiveSize(unittest.TestCase): members = [(str(data / ref / "a.bin"), f"{ref}/a.bin") for ref in ("pak", "old")] refs = {f"{ref}/a.bin": (ref, ("s",), ref, True) for ref in ("pak", "old")} listed = {entry["ref"]: entry for entry in - _manifest_data_directories(members, refs, registry, "")} + manifest_data_directories(members, refs, registry, "")} self.assertEqual(listed["pak"]["archive_size"], 21_360_579) self.assertNotIn("archive_size", listed["old"]) self.assertNotIn("optional", listed["pak"]) diff --git a/tests/test_region.py b/tests/test_region.py index 3e4ff9942..825a99489 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -13,7 +13,7 @@ import unittest from pathlib import Path from model import profiles as model_profiles -from model.profiles import _emulator_profiles_cache +from model.profiles import emulator_profiles_cache from model import region from resolve import regions as resolve_regions from packs.extras import emulator_region_drops @@ -476,10 +476,10 @@ class TestFallbackGroups(unittest.TestCase): ) def test_the_readme_names_a_slot_as_a_reader_does(self): - from packs.readme import _group_label + from packs.readme import group_label - self.assertEqual(_group_label("PicoDrive:variant:megacd"), "megacd (PicoDrive)") - self.assertEqual(_group_label("sega-mega-cd"), "sega-mega-cd") + self.assertEqual(group_label("PicoDrive:variant:megacd"), "megacd (PicoDrive)") + self.assertEqual(group_label("sega-mega-cd"), "sega-mega-cd") def test_no_requested_regions_reports_nothing(self): groups = {"fds": [("disksys.rom", "disksys.rom")]} @@ -698,13 +698,13 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): def test_the_report_withdraws_what_the_builder_withdraws(self): from model import profiles as model_profiles - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from packs import extras as packs_extras from packs import coverage tmp, root, db, config = self._fixture() try: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) groups, extra_dests = packs_extras.platform_region_groups( config, config["systems"], str(root / "emulators"), @@ -734,7 +734,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): "the report must withdraw exactly the builder's drop set", ) finally: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() tmp.cleanup() def test_a_missing_regional_core_file_is_withdrawn_too(self): @@ -742,7 +742,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): missing core file was never grouped and stayed "required missing" for a region the request excludes.""" from model import profiles as model_profiles - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from packs import coverage tmp, root, db, config = self._fixture() @@ -750,7 +750,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): jp = next(k for k, v in db["files"].items() if v["name"] == "jp.bin") del db["files"][jp] del db["indexes"]["by_name"]["jp.bin"] - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) plain = coverage.verify_platform( config, db, str(root / "emulators"), profiles, @@ -765,20 +765,20 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): {u["name"] for u in narrowed["undeclared_files"]}, {"us.bin"} ) finally: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() tmp.cleanup() def test_the_report_names_the_fallback_groups(self): """The pack README lists the systems kept whole because nothing answers the request. verify said all OK and named none.""" from model import profiles as model_profiles - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from packs import coverage from packs import report as packs_report tmp, root, db, config = self._fixture() try: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) result = coverage.verify_platform( config, db, str(root / "emulators"), profiles, @@ -790,7 +790,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): packs_report.print_platform_result(result, ["Demo"]) self.assertIn("all kept (1): demo-system", out.getvalue()) finally: - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() tmp.cleanup() def test_one_grouping_pass_serves_both_sides(self): @@ -1314,7 +1314,7 @@ class ARefusedRegionalFileHoldsNoSlot(unittest.TestCase): from packs.emulatorpack import generate_emulator_pack from packs.emulatorcheck import verify_emulator - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() repo = Path(__file__).resolve().parents[1] (repo / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=repo / "tmp")) @@ -1459,9 +1459,9 @@ class RegionWordsInAPackReadme(unittest.TestCase): """The pack README title-cased each slug: asia-ntsc read "Asia Ntsc".""" def test_the_priority_line_reads_as_written(self): - from packs.readme import _build_readme + from packs.readme import build_readme - readme = _build_readme( + readme = build_readme( "retroarch", "RetroArch", "system", 1, 1, regions=region.parse_requested("us,asia-ntsc,jp"), ) diff --git a/tests/test_region_held.py b/tests/test_region_held.py index 999152a5d..e1472cfe2 100644 --- a/tests/test_region_held.py +++ b/tests/test_region_held.py @@ -93,13 +93,13 @@ class ADataDirectoryCopyIsHeld(unittest.TestCase): def test_emulator_entry_from_a_data_tree(self): from packs.extras import _emulator_ships - from resolve.validation import _build_validation_index + from resolve.validation import build_validation_index profile = self.profiles["dolphin-mmjr2"] entry = next( fe for fe in profile["files"] if fe.get("name") == "nwc24msg.cfg" ) - index = _build_validation_index({"dolphin-mmjr2": profile}) + index = build_validation_index({"dolphin-mmjr2": profile}) self.assertTrue(_emulator_ships( entry, "dolphin-mmjr2", profile, self.db, index, {}, self.registry, )) diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index f6bdfd54a..9501950c0 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -262,7 +262,7 @@ class EverySurfaceSaysWhy(unittest.TestCase): line = guidepage.no_zip_line("KNULLI") self.assertEqual(line, "No ZIP for KNULLI. The command installs every file and checks it.") with contextlib.chdir(REPO_ROOT): - block = guidepage._pack_buttons("knulli") + block = guidepage.pack_buttons("knulli") guide = guidepage._guide_download( "knulli", "KNULLI", guides.GUIDES["knulli"], None, "## Download") self.assertIn(line, block) diff --git a/tests/test_required_only_twins.py b/tests/test_required_only_twins.py index b53841bd7..b1cd816f8 100644 --- a/tests/test_required_only_twins.py +++ b/tests/test_required_only_twins.py @@ -22,7 +22,7 @@ from pathlib import Path import yaml from model.platforms import _platform_config_cache -from model.profiles import _emulator_profiles_cache +from model.profiles import emulator_profiles_cache import generate_db from packs import manifest as packs_manifest from packs import platformpack @@ -72,7 +72,7 @@ class RequiredTwins(unittest.TestCase): yaml.dump({"platforms": {"twins": {"config": "twins.yml"}}}) ) _platform_config_cache.clear() - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() def tearDown(self): _platform_config_cache.clear() diff --git a/tests/test_save_root.py b/tests/test_save_root.py index 65883cbb4..6ccdd1f04 100644 --- a/tests/test_save_root.py +++ b/tests/test_save_root.py @@ -34,7 +34,7 @@ import yaml from packs.paths import ( EMULATOR_PACK_SAVE_FOLDER, SaveLayout, - _resolve_destination, + resolve_destination, save_destination, save_layout, ) @@ -86,10 +86,10 @@ class TheEntryNamesItsRoot(unittest.TestCase): def test_an_emulator_pack_keeps_them_in_their_own_folder(self): self.assertEqual( - _resolve_destination(self.ENTRY, False), + resolve_destination(self.ENTRY, False), f"{EMULATOR_PACK_SAVE_FOLDER}/CoreX/sysdata/keys.txt", ) - self.assertEqual(_resolve_destination(self.ENTRY, True), "sysdata/keys.txt") + self.assertEqual(resolve_destination(self.ENTRY, True), "sysdata/keys.txt") class ThePlatformNamesItsSaveDirectory(unittest.TestCase): @@ -211,13 +211,13 @@ class _Fixture(unittest.TestCase): OTHER_KEYS = b"PLATFORM KEYS" def setUp(self) -> None: - from model.profiles import _emulator_profiles_cache + from model.profiles import emulator_profiles_cache from model.platforms import _platform_config_cache - _emulator_profiles_cache.clear() + emulator_profiles_cache.clear() _platform_config_cache.clear() self.addCleanup(_platform_config_cache.clear) - self.addCleanup(_emulator_profiles_cache.clear) + self.addCleanup(emulator_profiles_cache.clear) self.root = _scratch(self) self.bios = self.root / "bios" self.platforms = self.root / "platforms" diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index 119e5858c..84d692930 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -934,7 +934,7 @@ class OneNativeIdOneSystem(unittest.TestCase): FOLDS = {"fbneo", "pcenginecd"} def test_scrapers_agree_on_every_shared_native_id(self): - from model.systems import _norm_system_id + from model.systems import norm_system_id seen: dict[str, dict[str, str]] = {} for path in sorted((REPO_ROOT / "scripts" / "scraper").glob("*_scraper.py")): @@ -947,7 +947,7 @@ class OneNativeIdOneSystem(unittest.TestCase): seen.setdefault(native.lower(), {})[path.stem] = slug split = { native: by for native, by in seen.items() - if native not in self.FOLDS and len({_norm_system_id(s) for s in by.values()}) > 1 + if native not in self.FOLDS and len({norm_system_id(s) for s in by.values()}) > 1 } self.assertEqual(split, {}) @@ -979,14 +979,14 @@ class OneNativeIdOneSystem(unittest.TestCase): def test_every_platform_system_meets_a_profile_system(self): import yaml - from model.systems import _norm_system_id + from model.systems import norm_system_id from model.profiles import load_emulator_profiles from model.platforms import load_platform_config known = set() for profile in load_emulator_profiles(str(REPO_ROOT / "emulators")).values(): - known |= {_norm_system_id(s) for s in profile.get("systems") or []} - known |= {_norm_system_id(f["system"]) for f in profile.get("files") or [] + known |= {norm_system_id(s) for s in profile.get("systems") or []} + known |= {norm_system_id(f["system"]) for f in profile.get("files") or [] if isinstance(f, dict) and f.get("system")} registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) for name in registry["platforms"]: @@ -994,22 +994,22 @@ class OneNativeIdOneSystem(unittest.TestCase): config = load_platform_config(name, str(REPO_ROOT / "platforms")) allowed = self.UNMATCHED["*"] | self.UNMATCHED.get(name, set()) stray = {s for s in config.get("systems", {}) - if _norm_system_id(s) not in known} - allowed + if norm_system_id(s) not in known} - allowed self.assertEqual(stray, set()) def test_xroar_machines_reach_the_platforms_that_run_it(self): import yaml - from model.systems import _norm_system_id + from model.systems import norm_system_id xroar = yaml.safe_load((REPO_ROOT / "emulators" / "xroar.yml").read_text()) - machines = {_norm_system_id(s) for s in xroar["systems"]} + machines = {norm_system_id(s) for s in xroar["systems"]} for platform, wanted in (("retrodeck", {"coco", "dragon64"}), ("recalbox", {"coco", "dragon64"}), ("misterfpga", {"coco3"})): with self.subTest(platform=platform): data = yaml.safe_load((REPO_ROOT / "platforms" / f"{platform}.yml").read_text()) - ids = {_norm_system_id(s) for s in data["systems"]} + ids = {norm_system_id(s) for s in data["systems"]} self.assertEqual(wanted & ids & machines, wanted) diff --git a/tests/test_site_arcade_boards.py b/tests/test_site_arcade_boards.py index 1902e8333..95b490266 100644 --- a/tests/test_site_arcade_boards.py +++ b/tests/test_site_arcade_boards.py @@ -68,7 +68,7 @@ STAYS_PLAIN = { def _reset() -> None: """Back to the repository's sections and boards, none written.""" siterender._arcade_source[0] = None - systemnames._boards_built[0] = False + systemnames.boards_built[0] = False systemnames._sections_installed[0] = False siterender.reset_console_pages() diff --git a/tests/test_site_availability.py b/tests/test_site_availability.py index 4bf56a582..c8a042ce7 100644 --- a/tests/test_site_availability.py +++ b/tests/test_site_availability.py @@ -16,8 +16,8 @@ from pathlib import Path import yaml from model.database import load_database -from sitegen.emulatorpage import _availability_check -from sitegen.emulatorcards import _file_badges +from sitegen.emulatorpage import availability_check +from sitegen.emulatorcards import file_badges REPO_ROOT = Path(__file__).resolve().parent.parent @@ -30,20 +30,20 @@ DB = { class UnsourceableIsNotHeld(unittest.TestCase): def test_a_homonym_does_not_stand_in(self): - available = _availability_check(DB, set()) + available = availability_check(DB, set()) self.assertTrue(available({"name": "pak0.pk3"})) self.assertFalse(available({"name": "pak0.pk3", "unsourceable": "retail data"})) def test_a_release_asset_is_held_only_when_collected(self): """storage: large_file said "in repo" for kenji-nx's user-picked firmware package, which the collection does not hold.""" - available = _availability_check(DB, set()) + available = availability_check(DB, set()) self.assertFalse(available({"name": ".zip", "storage": "large_file"})) self.assertTrue(available({"name": "pak0.pk3", "storage": "release"})) def test_the_badge_says_why(self): entry = {"name": "pak0.pk3", "unsourceable": "retail data"} - badges = " ".join(_file_badges(entry, False)) + badges = " ".join(file_badges(entry, False)) self.assertIn("unsourceable", badges) self.assertNotIn(">missing<", badges) self.assertNotIn("in repo", badges) @@ -52,7 +52,7 @@ class UnsourceableIsNotHeld(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): self.skipTest("database.json is not built") - available = _availability_check(load_database(str(db_path)), set()) + available = availability_check(load_database(str(db_path)), set()) shown_held = [] for path in sorted((REPO_ROOT / "emulators").glob("*.yml")): document = yaml.safe_load(path.read_text(encoding="utf-8")) or {} diff --git a/tests/test_site_bootstrap.py b/tests/test_site_bootstrap.py index 202fe9f8b..dd7266c20 100644 --- a/tests/test_site_bootstrap.py +++ b/tests/test_site_bootstrap.py @@ -261,10 +261,10 @@ class GeneratedSurfaces(unittest.TestCase): from sitegen import consolecards tail = " | sh -s -- --check" - self.assertEqual(consolecards._install_box_weight([f"curl -fsSL {INSTALL_SH}{tail}"]), + self.assertEqual(consolecards.install_box_weight([f"curl -fsSL {INSTALL_SH}{tail}"]), len("curl -fsSL ") + 66 + len(tail) + 1) line = f"&([scriptblock]::Create((irm {INSTALL_PS1}))) --check" - self.assertEqual(consolecards._install_box_weight([line]), + self.assertEqual(consolecards.install_box_weight([line]), len(line) - len(INSTALL_PS1) + 67 + 1) def test_the_readme_shows_the_short_form(self): diff --git a/tests/test_site_content_data.py b/tests/test_site_content_data.py index 538288efb..234036c15 100644 --- a/tests/test_site_content_data.py +++ b/tests/test_site_content_data.py @@ -213,7 +213,7 @@ class NavFromFrontMatter(unittest.TestCase): def test_every_wiki_page_states_its_place(self): for page in sorted(WIKI.glob("*.md")): - meta = decorate._front_matter(page.read_text(encoding="utf-8")) + meta = decorate.front_matter(page.read_text(encoding="utf-8")) with self.subTest(page=page.name): self.assertIn(meta.get("level"), sitegen_nav.TABS) self.assertTrue(meta.get("nav") is False or isinstance(meta.get("order"), int)) diff --git a/tests/test_site_cores.py b/tests/test_site_cores.py index 42a0031cd..6edb27987 100644 --- a/tests/test_site_cores.py +++ b/tests/test_site_cores.py @@ -40,7 +40,7 @@ class SiteCoreCounts(unittest.TestCase): } for name, cov in coverages.items(): with self.subTest(page=name): - if platformpage._own_list_only(cov["config"]): + if platformpage.own_list_only(cov["config"]): # cores: [] (MiSTer, BizHawk): no core table, the overview # row points at the platform's own list instead. self.assertNotIn(f"cross-reference-{name}", moved) diff --git a/tests/test_site_density_cards.py b/tests/test_site_density_cards.py index 2ca5b45e8..7ede7d42a 100644 --- a/tests/test_site_density_cards.py +++ b/tests/test_site_density_cards.py @@ -105,7 +105,7 @@ def _card() -> dict: class ASystemCardShowsTheAnswerFirst(unittest.TestCase): def setUp(self) -> None: - self.lines = cards._system_file_card(_card(), _card_consumers(SHA1)) + self.lines = cards.system_file_card(_card(), _card_consumers(SHA1)) self.text = "\n".join(self.lines) self.fold = self.text[self.text.index("")] self.shown = self.text.replace(self.fold, "") @@ -134,7 +134,7 @@ class ASystemCardShowsTheAnswerFirst(unittest.TestCase): # The yardstick list a page is cut by holds every fact: the # Starlight card holds each of its values. with markup.using("mkdocs"): - yardstick = "\n".join(cards._system_file_card(_card(), _card_consumers(SHA1))) + yardstick = "\n".join(cards.system_file_card(_card(), _card_consumers(SHA1))) for label, values in re.findall(r"(?m)^- ([^:]+): (.*)$", yardstick): self.assertIn(f"
    {label}
    ", self.text) for value in re.findall(r"[0-9a-f]{8,64}|`[^`]+`", values): @@ -152,7 +152,7 @@ class AnEmulatorCardFoldsItsHashes(unittest.TestCase): "required": True, "note": "Read at boot.", "priority": 5, "validation": ["md5"], "source_ref": "src/core/bios.cpp:47"} profile = {"emulator": "DuckStation", "files": [entry], "systems": ["sony-playstation"]} - self.text = "\n".join(emulatorcards._render_emulator_file( + self.text = "\n".join(emulatorcards.render_emulator_file( entry, profile, None, profile["files"], lambda _f: True, anchor="file-scph5501-bin")) self.fold = self.text[self.text.index("")] self.shown = self.text.replace(self.fold, "") @@ -176,7 +176,7 @@ class AnEmulatorCardFoldsItsHashes(unittest.TestCase): def test_the_markdown_yardstick_is_unchanged(self) -> None: with markup.using("mkdocs"): entry = {"name": "a.bin", "md5": "b" * 32, "size": 4} - text = "\n".join(emulatorcards._render_emulator_file( + text = "\n".join(emulatorcards.render_emulator_file( entry, {"files": [entry]}, None, [entry], lambda _f: True)) self.assertNotIn(" None: - self.text = "\n".join(install._console_install_block("PlayStation Portable", PAIRS)) + self.text = "\n".join(install.console_install_block("PlayStation Portable", PAIRS)) def test_one_command_per_tab_for_the_setup_picked(self) -> None: tabs = self.text[self.text.index("")] @@ -226,7 +226,7 @@ class AnInstallBoxShowsOneCommand(unittest.TestCase): self.assertIn("https://abdess.github.io", listed) def test_one_setup_keeps_its_two_blocks(self) -> None: - text = "\n".join(install._console_install_block("PlayStation Portable", PAIRS[:1])) + text = "\n".join(install.console_install_block("PlayStation Portable", PAIRS[:1])) self.assertNotIn("Setup