From 61e302d8f626ec4feaf2db7e742e429f9f760d82 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:24:02 +0100 Subject: [PATCH] refactor: make names shared across modules public --- scripts/profiling/reportinputs.py | 14 +-- scripts/profiling/resolver.py | 28 ++--- scripts/resolve/launcherplaces.py | 4 +- scripts/resolve/launchers.py | 6 +- scripts/resolve/localfile.py | 56 ++++----- scripts/resolve/lookup.py | 26 ++--- scripts/resolve/namestages.py | 36 +++--- scripts/resolve/truth.py | 42 +++---- scripts/resolve/truthsystems.py | 24 ++-- scripts/scraper/_hash_merge.py | 4 +- scripts/scraper/_hash_write.py | 28 ++--- scripts/scraper/_mame_sections.py | 38 +++--- scripts/scraper/batocera_config_writes.py | 14 +-- scripts/scraper/batocera_searches.py | 4 +- scripts/scraper/emuelec_launchers.py | 64 +++++------ scripts/scraper/emuelec_runs.py | 12 +- scripts/scraper/knulli_launchers.py | 6 +- scripts/scraper/recalbox_cascades.py | 32 +++--- scripts/scraper/recalbox_configgen.py | 56 ++++----- scripts/scraper/recalbox_emulators.py | 46 ++++---- scripts/scraper/recalbox_launchers.py | 38 +++--- scripts/scraper/retrobat_arguments.py | 30 ++--- scripts/scraper/retrobat_computers.py | 38 +++--- scripts/scraper/retrobat_config_files.py | 128 ++++++++++----------- scripts/scraper/retrobat_config_folders.py | 106 ++++++++--------- scripts/scraper/retrobat_generators.py | 34 +++--- scripts/scraper/retrobat_playstation.py | 18 +-- scripts/scraper/retrobat_render.py | 76 ++++++------ scripts/scraper/retrobat_xbox.py | 32 +++--- scripts/scraper/retrodeck_launchers.py | 26 ++--- scripts/scraper/retropie_launchers.py | 14 +-- scripts/scraper/retropie_reader.py | 74 ++++++------ scripts/scraper/retropie_scripts.py | 26 ++--- scripts/scraper/rocknix_configs.py | 8 +- scripts/scraper/rocknix_launchers.py | 16 +-- scripts/scraper/romfolders/es.py | 32 +++--- scripts/scraper/romfolders/esde.py | 16 +-- scripts/scraper/romfolders/packages.py | 16 +-- tests/test_audit_cli.py | 4 +- tests/test_hash_merge.py | 4 +- tests/test_launcher_evidence.py | 6 +- tests/test_launchers_retrobat_files.py | 4 +- tests/test_standalone_links.py | 4 +- tests/test_truth_layout.py | 14 +-- tests/test_tui_packs.py | 2 +- 45 files changed, 653 insertions(+), 653 deletions(-) diff --git a/scripts/profiling/reportinputs.py b/scripts/profiling/reportinputs.py index 5dc9b6967..777d618ba 100644 --- a/scripts/profiling/reportinputs.py +++ b/scripts/profiling/reportinputs.py @@ -32,7 +32,7 @@ from profiling.repos import ( ) -def _resolve_project_words( +def resolve_project_words( refs: list, tree_order: Callable[[], Iterable[list[str] | None]], link_order: Callable[[], Iterable[Iterable[str]]] = lambda: (), ) -> list: @@ -60,7 +60,7 @@ def _resolve_project_words( return out -def _path_roles(refs: list) -> dict[str, set[str]]: +def cited_path_roles(refs: list) -> dict[str, set[str]]: """The roles each cited path is written under across the profile.""" roles: dict[str, set[str]] = {} for *_, parts, _citation in refs: @@ -70,7 +70,7 @@ def _path_roles(refs: list) -> dict[str, set[str]]: return roles -def _check_build_refs( +def check_build_refs( profile: dict, deferred: list[tuple[Citation, dict]], views: list[RepoView], @@ -120,7 +120,7 @@ def _check_build_refs( return results -def _gather_refs( +def gather_refs( profile: dict, text: str | None ) -> tuple[list, list[tuple[Citation, dict]]]: """The citations to anchor, and the refs read at a shipped build instead. @@ -175,7 +175,7 @@ def _gather_refs( return refs, deferred -def _cited_dirs(refs: list) -> set[str]: +def cited_directories(refs: list) -> set[str]: """Directories the profile already cites, deepest first, to settle a bare filename that several trees of one repository carry.""" cited_dirs: set[str] = set() @@ -202,7 +202,7 @@ def _unanswered_skip(profile: dict) -> str: ) -def _readable_views( +def readable_views( profile: dict, report: ProfileReport, cache_dir: str, offline: bool ) -> list[RepoView] | None: """The repositories to read, None once the report says why it is skipped.""" @@ -251,7 +251,7 @@ def _readable_views( return views -def _record_revisions( +def record_revisions( profile: dict, report: ProfileReport, views: list[RepoView], cache_dir: str, offline: bool, ) -> dict[tuple[str, str], str]: diff --git a/scripts/profiling/resolver.py b/scripts/profiling/resolver.py index 3e20759dc..0bfb1dec6 100644 --- a/scripts/profiling/resolver.py +++ b/scripts/profiling/resolver.py @@ -42,13 +42,13 @@ from profiling.repos import ( reads_own_revision, ) from profiling.reportinputs import ( - _check_build_refs, - _cited_dirs, - _gather_refs, - _path_roles, - _readable_views, - _record_revisions, - _resolve_project_words, + check_build_refs, + cited_directories, + gather_refs, + cited_path_roles, + readable_views, + record_revisions, + resolve_project_words, ) @@ -635,14 +635,14 @@ def build_report( ) -> ProfileReport: """Confront one profile with its upstream.""" report = ProfileReport(name=name, entries=[], counts={}) - refs, deferred = _gather_refs(profile, text) - path_roles = _path_roles(refs) - cited_dirs = _cited_dirs(refs) + refs, deferred = gather_refs(profile, text) + path_roles = cited_path_roles(refs) + cited_dirs = cited_directories(refs) - views = _readable_views(profile, report, cache_dir, offline) + views = readable_views(profile, report, cache_dir, offline) if views is None: return report - tagged = _record_revisions(profile, report, views, cache_dir, offline) + tagged = record_revisions(profile, report, views, cache_dir, offline) # A profile carrying no source_ref still has a pin worth writing and a # version worth checking, so the revisions above are resolved first. @@ -653,10 +653,10 @@ def build_report( resolver = _Resolver( name, profile, cache_dir, offline, views, report, tagged, path_roles, cited_dirs ) - refs = _resolve_project_words( + refs = resolve_project_words( refs, resolver.trees_in_order, resolver.gitlinks_in_order ) - report.build_refs = _check_build_refs(profile, deferred, views, resolver.fetch_from) + report.build_refs = check_build_refs(profile, deferred, views, resolver.fetch_from) _judge_refs(resolver, refs, report) return report diff --git a/scripts/resolve/launcherplaces.py b/scripts/resolve/launcherplaces.py index bfcb4b65d..7a5d14c25 100644 --- a/scripts/resolve/launcherplaces.py +++ b/scripts/resolve/launcherplaces.py @@ -172,7 +172,7 @@ def set_by(entry: dict, passes_to: str) -> bool: return bool(key) and key in setting_tokens(passes_to) -def _bios_relative(directory: str, base: str) -> str | None: +def bios_relative(directory: str, base: str) -> str | None: """A launcher directory relative to the BIOS root, None when it is not one.""" directory = directory.strip().rstrip("/") roots = {base, "", *BIOS_ROOT_TOKENS} @@ -205,7 +205,7 @@ def record_directories(record: dict, base: str) -> list[str] | None: for part in re.split(r",|\bthen\b|\belse\b", text): if not part.strip(): continue - relative = _bios_relative(part, base) + relative = bios_relative(part, base) if relative is None: return [] if relative not in found: diff --git a/scripts/resolve/launchers.py b/scripts/resolve/launchers.py index 0e12de8d4..47d0a2bd1 100644 --- a/scripts/resolve/launchers.py +++ b/scripts/resolve/launchers.py @@ -10,11 +10,11 @@ from model.declarations import CONFIGS_ROOT, ROMS_ROOT, declared_root, declared_ from model.launcherrecords import record_emulators from core.paths import sanitize_pack_path from resolve.launcherconfig import bound_launchers -from resolve.launcherplaces import _bios_relative, record_directories +from resolve.launcherplaces import bios_relative, record_directories # The names a platform's launch code gives its BIOS root, besides the -# base_destination _bios_relative reads: RetroPie's scriptmodules set +# base_destination bios_relative reads: RetroPie's scriptmodules set # biosdir="$home/RetroPie/BIOS", EmuDeck's scripts ${biosPath}, RetroDECK's # component scripts $bios_path. BIOS_ROOT_VARIABLES = ("$biosdir", "$home/RetroPie/BIOS", "${biosPath}", "$bios_path") @@ -96,7 +96,7 @@ def ini_keys(passes_to: str) -> frozenset[str]: def _folder_in_bios(directory: str, base: str) -> str | None: """A directory relative to the BIOS root, None when it lies outside.""" - relative = _bios_relative(directory, base) + relative = bios_relative(directory, base) if relative is not None: return relative directory = directory.strip().rstrip("/") diff --git a/scripts/resolve/localfile.py b/scripts/resolve/localfile.py index 1916a2a9e..5e1ad730e 100644 --- a/scripts/resolve/localfile.py +++ b/scripts/resolve/localfile.py @@ -24,14 +24,14 @@ from resolve.ownership import ( owner_tokens, system_makers, ) -from resolve.lookup import Resolution, _Lookup, _entry_hint, _lookup, _record_match_status +from resolve.lookup import Resolution, Lookup, entry_hint, lookup, record_match_status from resolve.namestages import ( - _by_name, - _by_zip_contents, - _named_candidates, - _named_md5_match, - _ranked_mismatch, - _zipped_named, + name_or_alias_match, + by_zip_contents, + named_candidates, + named_md5_match, + ranked_mismatch, + zipped_named, ) @@ -122,16 +122,16 @@ def _rank_tail_candidates( ) -def _held_record(q: _Lookup, match_sha1: str) -> Resolution | None: +def _held_record(q: Lookup, match_sha1: str) -> Resolution | None: """The record's path and evidence, when it satisfies the entry and is on disk.""" path = q.files_db[match_sha1]["path"] - status = _record_match_status(q, match_sha1) + status = record_match_status(q, match_sha1) if status and os.path.exists(path): return path, status return None -def _by_sha1(q: _Lookup) -> Resolution | None: +def _by_sha1(q: Lookup) -> Resolution | None: """SHA1 exact match (accept list-valued sha1 from profiles).""" for cand in q.sha1_candidates: if cand in q.files_db: @@ -141,7 +141,7 @@ def _by_sha1(q: _Lookup) -> Resolution | None: return None -def _by_sha256(q: _Lookup) -> Resolution | None: +def _by_sha256(q: Lookup) -> Resolution | None: """SHA256 exact match, through the by_sha256 index.""" if not q.sha256_candidates: return None @@ -155,7 +155,7 @@ def _by_sha256(q: _Lookup) -> Resolution | None: return None -def _by_crc32(q: _Lookup) -> Resolution | None: +def _by_crc32(q: Lookup) -> Resolution | None: """CRC32 lookup, only when no stronger hash is declared.""" if ( not q.crc_candidates @@ -182,7 +182,7 @@ def _by_crc32(q: _Lookup) -> Resolution | None: return None -def _md5_hits(q: _Lookup) -> Iterator[tuple[str, str, str]]: +def _md5_hits(q: Lookup) -> Iterator[tuple[str, str, str]]: """Each held record a declared md5 names: path, evidence, md5 asked. Skipped for zipped_file: the md5 is the inner ROM's, not the container's. @@ -207,7 +207,7 @@ def _named_or_variant(names: frozenset[str], candidate_path: str) -> bool: return any(bn.startswith(n + ".") for n in names) -def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> list[str]: +def _tail_candidates(q: Lookup, start: int, tail: str, owners: set[str]) -> list[str]: """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, @@ -228,7 +228,7 @@ def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> lis return candidates -def _tail_match(q: _Lookup, candidates: list[str]) -> Resolution | None: +def _tail_match(q: Lookup, candidates: list[str]) -> Resolution | None: """The first candidate of a tail on disk that the entry accepts.""" for match_sha1 in candidates: if match_sha1 not in q.files_db: @@ -247,13 +247,13 @@ def _tail_match(q: _Lookup, candidates: list[str]) -> Resolution | None: ): continue return path, "path_exact" - status = _record_match_status(q, match_sha1) + status = record_match_status(q, match_sha1) if status: return path, status return None -def _by_path_suffix(q: _Lookup) -> tuple[Resolution | None, bool]: +def _by_path_suffix(q: Lookup) -> tuple[Resolution | None, bool]: """The file at the destination's tail, and whether the indexed one is absent.""" own_file_absent = False if not (q.dest_hint and q.by_path_suffix): @@ -296,7 +296,7 @@ def _by_path_suffix(q: _Lookup) -> tuple[Resolution | None, bool]: return None, own_file_absent -def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution | None: +def _by_data_dir_tail(q: Lookup, data_dir_registry: dict | None) -> Resolution | None: """The same tail in a data directory, for a platform's hashless entry.""" # by_path_suffix indexes bios/ # only, so AmberELEC's Machines/MSX - Arabic/config.ini fell through to @@ -322,7 +322,7 @@ def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution def _by_mame_clone( - q: _Lookup, zip_contents: dict | None, depth: int, data_dir_registry: dict | None + q: Lookup, zip_contents: dict | None, depth: int, data_dir_registry: dict | None ) -> Resolution | None: """If a file was deduped, resolve via canonical.""" clone_map = get_mame_clone_map(q.db.get("bios_dir")) @@ -351,7 +351,7 @@ def _by_mame_clone( return None -def _in_data_dirs(q: _Lookup, data_dir_registry: dict) -> tuple[Resolution | None, str | None]: +def _in_data_dirs(q: Lookup, data_dir_registry: dict) -> tuple[Resolution | None, str | None]: """Data directory fallback: scan data/ caches for matching filename.""" verdict = functools.partial( declared_hash_verdict, @@ -436,7 +436,7 @@ def resolve_local_file( A path or filename is never allowed to override a declared strong hash. """ - dest_hint = _entry_hint(file_entry, dest_hint) + dest_hint = entry_hint(file_entry, dest_hint) # A launcher that moves the layout (EmuDeck links azahar's sysdata to # bios/azahar/keys) changes where the file goes, not the tail the # collection indexes it under. Both are asked, and the stronger proof @@ -459,7 +459,7 @@ def resolve_local_file( # the container's own md5: neocd.bin's md5 is also the composite of a # one-member neocdz.zip, and the raw ROM shipped under the archive's name. composite_only = file_entry.get("zip_digest") == "composite" - q = _lookup( + q = lookup( file_entry, db, _name_as_hint(file_entry.get("name", ""), dest_hint), [cut_owners.get(value, value) for value in md5_list], composite_only=composite_only, @@ -521,25 +521,25 @@ def resolve_local_file( makers: frozenset[str] = frozenset() if has_strong_hash else system_makers(file_entry, db) if not has_strong_hash and not unsourceable: - found, unsourceable = _by_name(q, makers, data_dir_registry) + found, unsourceable = name_or_alias_match(q, makers, data_dir_registry) if found: return found # 4. Name + alias fallback with md5_composite + direct MD5 per candidate - named = _named_candidates(q, makers) + named = named_candidates(q, makers) if named: - found = _named_md5_match(q, named) + found = named_md5_match(q, named) if q.zipped_file: - found = found or _zipped_named(q, named, q.zipped_file) + found = found or zipped_named(q, named, q.zipped_file) elif not unsourceable: - found = found or _ranked_mismatch(q, named) + found = found or ranked_mismatch(q, named) if found: return found # 5. zipped_file content match via pre-built index (last resort: # matches inner ROM MD5 across ALL ZIPs in the repo, so only use # when name-based resolution failed entirely) - found = _by_zip_contents(q, zip_contents) + found = by_zip_contents(q, zip_contents) # MAME clone fallback: if a file was deduped, resolve via canonical. The # clone name is a name step like the others: an unsourceable entry skips diff --git a/scripts/resolve/lookup.py b/scripts/resolve/lookup.py index cb2e98e7d..ae7d274f9 100644 --- a/scripts/resolve/lookup.py +++ b/scripts/resolve/lookup.py @@ -27,7 +27,7 @@ Resolution = tuple[str, str] @dataclass(frozen=True) -class _Lookup: +class Lookup: """One entry as resolve_local_file reads it: its names and declared hashes.""" file_entry: dict @@ -76,9 +76,9 @@ def _lookup_names(name: str, aliases: list, dest_hint: str) -> tuple[list[str], return names_to_try, own_names -def _lookup( +def lookup( file_entry: dict, db: dict, dest_hint: str, md5_list: list[str], *, composite_only: bool -) -> _Lookup: +) -> Lookup: """Read the names and every declared hash of an entry once.""" sha1 = file_entry.get("sha1") name = file_entry.get("name", "") @@ -107,7 +107,7 @@ def _lookup( if candidate.strip() ) indexes = db.get("indexes", {}) - return _Lookup( + return Lookup( file_entry=file_entry, db=db, dest_hint=dest_hint, @@ -127,7 +127,7 @@ def _lookup( ) -def _record_match_status(q: _Lookup, match_sha1: str) -> str | None: +def record_match_status(q: Lookup, match_sha1: str) -> str | None: """Return hash evidence when a DB record satisfies every declaration.""" entry = q.files_db.get(match_sha1) if not entry: @@ -174,7 +174,7 @@ def held_record_for(file_entry: dict, db: dict) -> str | None: (cut_md5_owner(value, by_md5) or value) if len(value) < 32 else value for value in parse_hash_list(file_entry.get("md5")) ] - q = _lookup( + q = lookup( file_entry, db, "", md5_list, composite_only=file_entry.get("zip_digest") == "composite", ) @@ -187,7 +187,7 @@ def held_record_for(file_entry: dict, db: dict) -> str | None: if not (q.sha1_candidates or q.sha256_candidates or q.md5_list or q.zipped_file): candidates += [indexes.get("by_crc32", {}).get(v) for v in q.crc_candidates] return next( - (c for c in candidates if c and c in q.files_db and _record_match_status(q, c)), + (c for c in candidates if c and c in q.files_db and record_match_status(q, c)), None, ) @@ -203,8 +203,8 @@ def variant_copies( A copy passes the shape the entry's code checks and, when the entry declares hashes, agrees with every one of them, as the resolver requires. """ - q = _lookup( - file_entry, db, _entry_hint(file_entry, dest_hint), [ + q = lookup( + file_entry, db, entry_hint(file_entry, dest_hint), [ (cut_md5_owner(value, db.get("indexes", {}).get("by_md5", {})) or value) if len(value) < 32 else value for value in parse_hash_list(file_entry.get("md5")) @@ -229,8 +229,8 @@ def variant_copies( os.path.dirname(os.path.normpath(path)) == home and os.path.normpath(path) != primary and variant_base_name(os.path.basename(path)) in names - and (not hashed or _record_match_status(q, match_sha1)) - and _name_size_ok(q, match_sha1) + and (not hashed or record_match_status(q, match_sha1)) + and name_size_ok(q, match_sha1) and os.path.exists(path) and path not in out ): @@ -238,7 +238,7 @@ def variant_copies( return out -def _name_size_ok(q: _Lookup, match_sha1: str) -> bool: +def name_size_ok(q: Lookup, match_sha1: str) -> bool: """Whether a record found by name has the shape the entry's code checks.""" record = q.files_db.get(match_sha1, {}) return name_match_size_ok(q.file_entry, record.get("size")) and adler32_fits( @@ -246,7 +246,7 @@ def _name_size_ok(q: _Lookup, match_sha1: str) -> bool: ) and content_fits(q.file_entry, record.get("path", "")) -def _entry_hint(file_entry: dict, dest_hint: str) -> str: +def entry_hint(file_entry: dict, dest_hint: str) -> str: """The destination tail the collection indexes the entry under.""" # A platform that hands each core a system directory of its own (MinUI's # Bios//) writes that folder in front of the core's path. The tail diff --git a/scripts/resolve/namestages.py b/scripts/resolve/namestages.py index cc28e8553..03dbcbb54 100644 --- a/scripts/resolve/namestages.py +++ b/scripts/resolve/namestages.py @@ -23,7 +23,7 @@ from resolve.content import ( shape_fits, ) from resolve.datadirs import resolve_in_data_dirs -from resolve.lookup import Resolution, _Lookup, _name_size_ok +from resolve.lookup import Resolution, Lookup, name_size_ok from resolve.ownership import ( affinity_tokens, engine_tree, @@ -83,7 +83,7 @@ def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str return sorted(paths, key=score, reverse=True) -def _exact_name_candidates(q: _Lookup) -> list[str]: +def _exact_name_candidates(q: Lookup) -> list[str]: """The held files answering to the entry's names, exact casing.""" candidates: list[str] = [] # The entry's own names first, the destination's basename only when @@ -99,7 +99,7 @@ def _exact_name_candidates(q: _Lookup) -> list[str]: for match_sha1 in ( by_proven_name.get(try_name) or q.by_name.get(try_name, []) ): - if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + if match_sha1 in q.files_db and name_size_ok(q, match_sha1): path = q.files_db[match_sha1]["path"] if os.path.exists(path) and path not in candidates: candidates.append(path) @@ -108,7 +108,7 @@ def _exact_name_candidates(q: _Lookup) -> list[str]: return candidates -def _add_variant_primaries(q: _Lookup, candidates: list[str]) -> None: +def _add_variant_primaries(q: Lookup, candidates: list[str]) -> None: """Add the primaries that variants answering the exact casing stand in for.""" # Only variants answer the exact casing, but the primary they # stand in for may be stored under another one: x1 asked for @@ -127,14 +127,14 @@ def _add_variant_primaries(q: _Lookup, candidates: list[str]) -> None: "/.variants/" not in path and os.path.dirname(path) in homes and os.path.basename(path).casefold() == wanted - and _name_size_ok(q, match_sha1) + and name_size_ok(q, match_sha1) and os.path.exists(path) and path not in candidates ): candidates.append(path) -def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str]) -> None: +def _add_casefold_candidates(q: Lookup, candidates: list[str], owners: set[str]) -> None: """Add the held files answering to the entry's names in another casing.""" # Case-insensitive fallback: upstream platforms disagree on # casing (VEC_MineStorm.vec vs VEC_Minestorm.vec). Two casings @@ -148,7 +148,7 @@ def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str] folded = _casefold_name_index(q.by_name) for try_name in q.names_to_try: for match_sha1 in folded.get(try_name.casefold(), []): - if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + 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): continue @@ -156,7 +156,7 @@ def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str] candidates.append(path) -def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> list[str]: +def _same_maker(q: Lookup, candidates: list[str], makers: frozenset[str]) -> list[str]: """The candidates filed under the system's maker, or its shadowed aliases.""" candidates = [p for p in candidates if not other_maker(p, makers, q.db)] if candidates: @@ -173,7 +173,7 @@ def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> li if ( maker_folder(path, str(q.db.get("bios_dir") or "bios")) in makers - and _name_size_ok(q, match_sha1) + and name_size_ok(q, match_sha1) and os.path.exists(path) and path not in candidates ): @@ -182,7 +182,7 @@ def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> li def _choose_by_name( - q: _Lookup, + q: Lookup, candidates: list[str], owners: set[str], exact_foreign: bool, @@ -244,8 +244,8 @@ def _choose_by_name( return chosen, "name_exact" -def _by_name( - q: _Lookup, makers: frozenset[str], data_dir_registry: dict | None +def name_or_alias_match( + q: Lookup, makers: frozenset[str], data_dir_registry: dict | None ) -> tuple[Resolution | None, bool]: """Any file with that name or alias (existence check). @@ -287,7 +287,7 @@ def _by_name( return _choose_by_name(q, candidates, owners, exact_foreign, data_dir_registry), False -def _named_candidates(q: _Lookup, makers: frozenset[str]) -> list[tuple[str, str, int | None]]: +def named_candidates(q: Lookup, makers: frozenset[str]) -> list[tuple[str, str, int | None]]: """Every held file of the entry's names: path, md5, size.""" named: list[tuple[str, str, int | None]] = [] seen_paths = set() @@ -320,7 +320,7 @@ def _named_candidates(q: _Lookup, makers: frozenset[str]) -> list[tuple[str, str return named -def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution | None: +def named_md5_match(q: Lookup, named: list[tuple[str, str, int | None]]) -> Resolution | None: """A named file whose md5, or archive composite, is a declared one. Sorts *named* in place for a composite-only entry, as the steps after @@ -350,8 +350,8 @@ def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Re return None -def _zipped_named( - q: _Lookup, named: list[tuple[str, str, int | None]], zipped_file: str +def zipped_named( + q: Lookup, named: list[tuple[str, str, int | None]], zipped_file: str ) -> Resolution | None: """When zipped_file is set, only accept candidates that contain it.""" valid = [] @@ -376,14 +376,14 @@ def _zipped_named( return None -def _ranked_mismatch(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution: +def ranked_mismatch(q: Lookup, named: list[tuple[str, str, int | None]]) -> Resolution: """The named file the entry would take, reported as a hash mismatch.""" ordered = _by_affinity([c[0] for c in named], q.file_entry, q.dest_hint) primary = [c for c in ordered if "/.variants/" not in c] return (primary[0] if primary else ordered[0]), "hash_mismatch" -def _by_zip_contents(q: _Lookup, zip_contents: dict | None) -> Resolution | None: +def by_zip_contents(q: Lookup, zip_contents: dict | None) -> Resolution | None: """zipped_file content match via pre-built index. Last resort: matches inner ROM MD5 across ALL ZIPs in the repo, so only diff --git a/scripts/resolve/truth.py b/scripts/resolve/truth.py index 2b3d205ee..bc4ace09d 100644 --- a/scripts/resolve/truth.py +++ b/scripts/resolve/truth.py @@ -17,15 +17,15 @@ from resolve.entryscope import ( installed_with_emulator, ) from resolve.truthsystems import ( - _SystemMap, - _brought, - _cover, - _enrich_hashes, - _has_exploitable_data, - _platform_entries, - _require_by_slot, - _serialize_systems, - _sizes_clash, + SystemMap, + brought_by, + cover, + enrich_hashes, + has_exploitable_data, + platform_entries, + require_by_slot, + serialize_systems, + sizes_clash, ) @@ -151,7 +151,7 @@ def _shares_hash(a: dict, b: dict) -> bool: def _contents_disagree(a: dict, b: dict) -> bool: """A hash both declare without a value in common, or no size both admit.""" - return contradicts(declared_hashes(a), declared_hashes(b)) or _sizes_clash(a, b) + return contradicts(declared_hashes(a), declared_hashes(b)) or sizes_clash(a, b) def _fold_into(existing: dict, file_entry: dict, emu_name: str) -> None: @@ -160,7 +160,7 @@ def _fold_into(existing: dict, file_entry: dict, emu_name: str) -> None: existing["_cores"] = existing.get("_cores", set()) | {emu_name} if file_entry.get("_opens_by_name", True): existing["_named_by"] = existing.get("_named_by", set()) | {emu_name} - existing["_brought_by"] = existing.get("_brought_by", set()) | _brought(file_entry, emu_name) + existing["_brought_by"] = existing.get("_brought_by", set()) | brought_by(file_entry, emu_name) sr = file_entry.get("source_ref") if sr is not None: sr_key = _serialize_source_ref(sr) @@ -310,11 +310,11 @@ def _new_truth_entry(file_entry: dict, emu_name: str, db: dict | None) -> dict: if grouped: _fold_set_member(entry, file_entry, emu_name) entry["_named_by"] = {emu_name} if file_entry.get("_opens_by_name", True) else set() - entry["_brought_by"] = _brought(file_entry, emu_name) + entry["_brought_by"] = brought_by(file_entry, emu_name) sr = file_entry.get("source_ref") entry["_source_refs"] = {_serialize_source_ref(sr)} if sr is not None else set() if db: - _enrich_hashes(entry, db) + enrich_hashes(entry, db) # Which core gave each hash, for the conflict warning. Dropped before # the model is written. entry["_hash_by"] = {h: emu_name for h in HASH_FIELDS if entry.get(h)} @@ -440,7 +440,7 @@ def generate_platform_truth( # 1. File-based: if the scraped platform already has this file, use its system # 2. Exact match: profile system ID == platform system ID # 3. Normalized match: strip manufacturer prefix + separators - mapping = _SystemMap.of(config, db) + mapping = SystemMap.of(config, db) systems: dict[str, dict] = {} unattributed: dict[str, int] = {} @@ -459,7 +459,7 @@ def generate_platform_truth( on_platform = { mapping.map_sys_id(sid) for sid in profile.get("systems", []) } & mapping.platform_sys_ids - for fe in _platform_entries(emu_name, profile, launches, platform_name): + for fe in platform_entries(emu_name, profile, launches, platform_name): sys_targets = mapping.targets(fe, profile, on_platform) if not sys_targets: unattributed[emu_name] = unattributed.get(emu_name, 0) + 1 @@ -469,7 +469,7 @@ def generate_platform_truth( _merge_file_into_system( system, fe if position == 0 else copy.deepcopy(fe), emu_name, db ) - _cover(system_cores, sys_id, "profiled", emu_name) + cover(system_cores, sys_id, "profiled", emu_name) # Ensure all systems of resolved cores have entries (even with 0 files). # This documents that the system is covered: the core was analyzed and @@ -480,12 +480,12 @@ def generate_platform_truth( for prof_sid in profile.get("systems", []): sys_id = mapping.map_sys_id(prof_sid) systems.setdefault(sys_id, {}) - _cover(system_cores, sys_id, "profiled", emu_name) + cover(system_cores, sys_id, "profiled", emu_name) # Track unprofiled cores per system based on profile system lists for emu_name in cores_unprofiled: for sys_id in systems: - _cover(system_cores, sys_id, "unprofiled", emu_name) + cover(system_cores, sys_id, "unprofiled", emu_name) _fold_data_directory_readers( systems, profiles, sorted(cores_profiled), launches, platform_name, @@ -493,7 +493,7 @@ def generate_platform_truth( ) for sys_data in systems.values(): - _require_by_slot(sys_data.get("files", [])) + require_by_slot(sys_data.get("files", [])) # Drop files with no exploitable data AFTER all cores have contributed. # A file declared by one core without hash/size/path may be enriched by @@ -502,9 +502,9 @@ def generate_platform_truth( for sys_data in systems.values(): files_list = sys_data.get("files", []) if files_list: - sys_data["files"] = [fe for fe in files_list if _has_exploitable_data(fe)] + sys_data["files"] = [fe for fe in files_list if has_exploitable_data(fe)] - _serialize_systems(systems, system_cores) + serialize_systems(systems, system_cores) return { "platform": platform_name, diff --git a/scripts/resolve/truthsystems.py b/scripts/resolve/truthsystems.py index 9b7460459..87a7b6362 100644 --- a/scripts/resolve/truthsystems.py +++ b/scripts/resolve/truthsystems.py @@ -19,7 +19,7 @@ from resolve.launches import PlatformLaunches from resolve.standalone import platform_layouts -def _enrich_hashes(entry: dict, db: dict) -> None: +def enrich_hashes(entry: dict, db: dict) -> None: """Fill the hashes a profile omits from the record its own hash names. The record is found by sha1, sha256, then md5, then crc32 with the size @@ -60,7 +60,7 @@ def _enrich_hashes(entry: dict, db: dict) -> None: entry["size"] = record["size"] -def _require_by_slot(files: list[dict]) -> None: +def require_by_slot(files: list[dict]) -> None: """A core that requires a name an entry answers for requires the entry. Merged by name, one core's alternatives land in several entries. Ymir @@ -90,7 +90,7 @@ def _require_by_slot(files: list[dict]) -> None: entry["required"] = True -def _brought(file_entry: dict, emu_name: str) -> set[str]: +def brought_by(file_entry: dict, emu_name: str) -> set[str]: """The core and build that need the file brought, empty when the emulator installs it. An entry read without layer (a test, a caller of its own) is brought by its core's libretro build.""" @@ -98,7 +98,7 @@ def _brought(file_entry: dict, emu_name: str) -> set[str]: return {brought} if brought else set() -def _has_exploitable_data(entry: dict) -> bool: +def has_exploitable_data(entry: dict) -> bool: """Check if an entry has any data beyond its name that can drive verification. Applied AFTER merging all cores so entries benefit from enrichment by @@ -189,7 +189,7 @@ def _sizes(entry: dict) -> tuple[set[int], tuple[int, float] | None]: return exact, (low or 0, float("inf") if high is None else high) -def _sizes_clash(a: dict, b: dict) -> bool: +def sizes_clash(a: dict, b: dict) -> bool: """No size both entries admit, lists and windows included.""" exact_a, window_a = _sizes(a) exact_b, window_b = _sizes(b) @@ -210,7 +210,7 @@ def _identity(entry: dict, db: dict | None) -> dict: """The entry with the hashes and size the database knows for its hash.""" probe = {k: entry[k] for k in ("sha1", "md5", "crc32", "size") if entry.get(k)} if db and probe and not any(isinstance(v, list) for v in probe.values()): - _enrich_hashes(probe, db) + enrich_hashes(probe, db) return {**entry, **{k: v for k, v in probe.items() if not entry.get(k)}} @@ -232,13 +232,13 @@ def _declaration_verdict(entry: dict, declaration: dict, db: dict | None) -> str ours, theirs = _identity(entry, db), _identity(declaration, db) if _identity_values(ours) & _identity_values(theirs): return "same" - if _sizes_clash(ours, theirs): + if sizes_clash(ours, theirs): return "other" return "undecided" @dataclass(frozen=True) -class _SystemMap: +class SystemMap: """How a profile's systems and entries map onto a platform's systems.""" platform_sys_ids: set[str] @@ -252,7 +252,7 @@ class _SystemMap: db: dict | None @classmethod - def of(cls, config: dict, db: dict | None) -> _SystemMap: + def of(cls, config: dict, db: dict | None) -> SystemMap: declared_by_name: dict[str, list[tuple[str, dict]]] = {} for psid, sys_data in config.get("systems", {}).items(): for fe in sys_data.get("files", []): @@ -333,7 +333,7 @@ class _SystemMap: return sys_targets -def _cover( +def cover( system_cores: dict[str, dict[str, set[str]]], sys_id: str, kind: str, emu_name: str, ) -> None: sys_cov = system_cores.setdefault( @@ -346,7 +346,7 @@ def _cover( sys_cov[kind].add(emu_name) -def _platform_entries( +def platform_entries( emu_name: str, profile: dict, launches: PlatformLaunches, platform_name: str, ) -> list[dict]: # The pack's rule (validation.deliverable), per build: a file the @@ -365,7 +365,7 @@ def _platform_entries( ]) -def _serialize_systems( +def serialize_systems( systems: dict[str, dict], system_cores: dict[str, dict[str, set[str]]], ) -> None: # Convert sets to sorted lists for serialization diff --git a/scripts/scraper/_hash_merge.py b/scripts/scraper/_hash_merge.py index cb15a05a7..a75e97c18 100644 --- a/scripts/scraper/_hash_merge.py +++ b/scripts/scraper/_hash_merge.py @@ -260,7 +260,7 @@ def diff_mame( required_moved = old_entry.get("required", True) != settled_required(old_entry, set_data) - if _contents_differ(old_contents, new_contents) or ref_moved or required_moved: + if contents_differ(old_contents, new_contents) or ref_moved or required_moved: updated.append(set_name) else: unchanged += 1 @@ -399,7 +399,7 @@ def _build_source_ref(set_data: dict, role: str = "") -> str: return f"{role}{source_file}" -def _contents_differ(old: list[dict], new: list[dict]) -> bool: +def contents_differ(old: list[dict], new: list[dict]) -> bool: if len(old) != len(new): return True old_by_name = {c["name"]: c for c in old} diff --git a/scripts/scraper/_hash_write.py b/scripts/scraper/_hash_write.py index 30470397c..329f49042 100644 --- a/scripts/scraper/_hash_write.py +++ b/scripts/scraper/_hash_write.py @@ -33,7 +33,7 @@ def write_mame_profile(path: str | Path, data: dict) -> None: patched, "upstream_commit", data.get("upstream_commit", ""), after=("source_commit", "upstream"), ) - patched = _patch_bios_entries(patched, data.get("files", [])) + patched = patch_bios_entries(patched, data.get("files", [])) patched = _append_new_entries(patched, data.get("files", []), original) write_text_atomic(str(p), patched) @@ -162,12 +162,12 @@ def _patch_entry(lines: list[str], start_line: int, fe: dict) -> None: # Insert new contents after last owned line if contents: - new_lines = _format_contents(contents).split("\n") + new_lines = format_contents(contents).split("\n") for k, cl in enumerate(new_lines): lines.insert(last_owned + 1 + k, cl) -def _patch_bios_entries(text: str, files: list[dict]) -> str: +def patch_bios_entries(text: str, files: list[dict]) -> str: """Patch contents, source_ref and required of bios_zip entries in-place. Processes entries in reverse order to preserve line offsets. @@ -221,14 +221,14 @@ def _append_new_entries(text: str, files: list[dict], original: str) -> str: lines = [] profile_type = str(existing_data.get("type") or "") for fe in new_entries: - lines.append(f"\n - name: {_yaml_scalar(fe['name'])}") + lines.append(f"\n - name: {yaml_scalar(fe['name'])}") lines.extend(set_path_lines(profile_type, fe["name"])) lines.append(f" required: {str(fe['required']).lower()}") lines.append(" category: bios_zip") if fe.get("source_ref"): lines.append(f' source_ref: "{fe["source_ref"]}"') if fe.get("contents"): - lines.append(_format_contents(fe["contents"])) + lines.append(format_contents(fe["contents"])) if lines: # New BIOS root sets go before the generated sections, which run to @@ -242,13 +242,13 @@ def _append_new_entries(text: str, files: list[dict], original: str) -> str: return text -def _device_section_start(text: str) -> int | None: +def device_section_start(text: str) -> int | None: """Offset of the generated device section header, if the profile has one.""" match = re.search(rf"^{re.escape(DEVICE_SECTION)}$", text, re.M) return match.start() if match else None -def _softlist_section_start(text: str) -> int | None: +def softlist_section_start(text: str) -> int | None: """Offset of the generated software list section header, if any.""" match = re.search(rf"^{re.escape(SOFTLIST_SECTION)}$", text, re.M) return match.start() if match else None @@ -256,7 +256,7 @@ def _softlist_section_start(text: str) -> int | None: def generated_start(text: str) -> int | None: """Offset of the first generated section: what a reader wrote ends there.""" - found = [at for at in (_softlist_section_start(text), _device_section_start(text)) if at is not None] + found = [at for at in (softlist_section_start(text), device_section_start(text)) if at is not None] return min(found) if found else None @@ -276,7 +276,7 @@ def set_path_lines(profile_type: str, name: str) -> list[str]: return lines -def _yaml_scalar(value: object) -> str: +def yaml_scalar(value: object) -> str: """Quote a scalar so YAML reads back exactly what the source said. A MAME ROM named ``01`` written bare re-parses as the integer 1, and the @@ -285,13 +285,13 @@ def _yaml_scalar(value: object) -> str: return json.dumps(str(value), ensure_ascii=False) -def _format_contents(contents: list[dict]) -> str: +def format_contents(contents: list[dict]) -> str: """Format a contents list as YAML text.""" lines = [" contents:"] for rom in contents: - lines.append(f" - name: {_yaml_scalar(rom['name'])}") + lines.append(f" - name: {yaml_scalar(rom['name'])}") if rom.get("description"): - lines.append(f" description: {_yaml_scalar(rom['description'])}") + lines.append(f" description: {yaml_scalar(rom['description'])}") if rom.get("size"): lines.append(f" size: {rom['size']}") if rom.get("crc32"): @@ -397,8 +397,8 @@ def write_fbneo_profile(path: str | Path, data: dict) -> None: if new_roms: lines = [] for fe in new_roms: - lines.append(f" - name: {_yaml_scalar(fe['name'])}") - lines.append(f" archive: {_yaml_scalar(fe['archive'])}") + lines.append(f" - name: {yaml_scalar(fe['name'])}") + lines.append(f" archive: {yaml_scalar(fe['archive'])}") lines.append(f" required: {str(fe.get('required', True)).lower()}") if fe.get("size"): lines.append(f" size: {fe['size']}") diff --git a/scripts/scraper/_mame_sections.py b/scripts/scraper/_mame_sections.py index f37d3aa78..996355b9f 100644 --- a/scripts/scraper/_mame_sections.py +++ b/scripts/scraper/_mame_sections.py @@ -10,15 +10,15 @@ from pathlib import Path from core.artifacts import write_text_atomic from model.profiles import PROFILE_BACKUP_SUFFIX from model.safeparse import yaml_load -from ._hash_merge import _build_contents, _build_source_ref, _contents_differ, mame_ref_role +from ._hash_merge import _build_contents, _build_source_ref, contents_differ, mame_ref_role from ._hash_write import ( DEVICE_SECTION, SOFTLIST_SECTION, - _device_section_start, - _format_contents, - _patch_bios_entries, - _softlist_section_start, - _yaml_scalar, + device_section_start, + format_contents, + patch_bios_entries, + softlist_section_start, + yaml_scalar, generated_start, set_path_lines, ) @@ -49,7 +49,7 @@ def _device_note(description: str) -> str: def _zip_scalar(name: str) -> str: """An archive name as the written entries spell it: bare when YAML keeps it.""" - return name if re.fullmatch(r"[a-z0-9_]+\.zip", name) else _yaml_scalar(name) + return name if re.fullmatch(r"[a-z0-9_]+\.zip", name) else yaml_scalar(name) _PLAIN_SYSTEM = re.compile(r"^[a-z][a-z0-9-]*$") @@ -58,7 +58,7 @@ _PLAIN_SYSTEM = re.compile(r"^[a-z][a-z0-9-]*$") def _system_lines(systems: list[str]) -> list[str]: """`system:` for one system, `systems:` for several, nothing for none.""" def scalar(value: str) -> str: - return value if _PLAIN_SYSTEM.match(value) else _yaml_scalar(value) + return value if _PLAIN_SYSTEM.match(value) else yaml_scalar(value) if not systems: return [] @@ -76,7 +76,7 @@ def _entry_systems(entry: dict) -> list[str]: def _section_names(text: str) -> set[str]: """Entry names inside the generated device section.""" - start = _device_section_start(text) + start = device_section_start(text) if start is None: return set() end = _FILES_END.search(text, text.index("\n", start) + 1) @@ -95,7 +95,7 @@ def _set_section_systems(text: str, systems: dict[str, list[str]]) -> str: """ if not systems: return text - start = _device_section_start(text) + start = device_section_start(text) if start is None: return text return text[:start] + _rewrite_systems(text[start:], systems) @@ -146,7 +146,7 @@ def _format_device_entry(name: str, device: dict, role: str, profile_type: str = break_on_hyphens=False, ) ) - lines.append(_format_contents(_device_contents(device["roms"], []))) + lines.append(format_contents(_device_contents(device["roms"], []))) return "\n".join(lines) @@ -201,7 +201,7 @@ def merge_mame_devices( old = existing[0] contents = _device_contents(device["roms"], old.get("contents") or []) changed = False - if _contents_differ(old.get("contents") or [], contents): + if contents_differ(old.get("contents") or [], contents): contents_patches.append({"name": name, "category": "bios_zip", "contents": contents}) changed = True if not old.get("source_ref") and device.get("source_line"): @@ -219,7 +219,7 @@ def merge_mame_devices( if write and (contents_patches or ref_patches or system_patches or new_blocks): patched = _add_source_refs(text, ref_patches) patched = _set_section_systems(patched, system_patches) - patched = _patch_bios_entries(patched, contents_patches) + patched = patch_bios_entries(patched, contents_patches) patched = _insert_device_entries(patched, new_blocks) shutil.copy2(path, path.with_suffix(PROFILE_BACKUP_SUFFIX)) write_text_atomic(str(path), patched) @@ -244,8 +244,8 @@ def _softlist_section(profile: dict, lists: dict[str, list[str]], role: str) -> base = str(tree.get("path") or tree["name"]) for name, systems in sorted(lists.items()): lines = [ - f" - name: {_yaml_scalar(name + '.xml')}", - f" path: {_yaml_scalar(base + name + '.xml')}", + f" - name: {yaml_scalar(name + '.xml')}", + f" path: {yaml_scalar(base + name + '.xml')}", ] if tree.get("mode"): lines.append(f" mode: {tree['mode']}") @@ -291,9 +291,9 @@ def merge_mame_support( role = mame_ref_role(profile) original = text - start = _softlist_section_start(text) + start = softlist_section_start(text) if start is not None: - device = _device_section_start(text) + device = device_section_start(text) if device is not None and device > start: end = device else: @@ -364,7 +364,7 @@ def _insert_device_entries(text: str, blocks: dict[str, str]) -> str: """ if not blocks: return text - start = _device_section_start(text) + start = device_section_start(text) if start is None: files_at = re.search(r"^files:[ \t]*$", text, re.M) if files_at is None or _FILES_END.search(text, files_at.end()): @@ -372,7 +372,7 @@ def _insert_device_entries(text: str, blocks: dict[str, str]) -> str: "files: must be the last top-level key to hold a device section" ) text = text.rstrip("\n") + "\n\n" + DEVICE_SECTION + "\n" - start = _device_section_start(text) + start = device_section_start(text) body_at = text.index("\n", start) + 1 end_match = _FILES_END.search(text, body_at) end = end_match.start() if end_match else len(text) diff --git a/scripts/scraper/batocera_config_writes.py b/scripts/scraper/batocera_config_writes.py index 8e38feb61..e0f71527d 100644 --- a/scripts/scraper/batocera_config_writes.py +++ b/scripts/scraper/batocera_config_writes.py @@ -6,7 +6,7 @@ import ast from collections.abc import Callable from .batocera_configgen import Configgen, _path_value -from .batocera_searches import _option_names +from .batocera_searches import option_names from .configgen_launchers import ( Launcher, Source, @@ -78,7 +78,7 @@ def melonds(cg: Configgen) -> list[Launcher]: node for node in ast.walk(generate) if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]).startswith("base_config['Emu']['ConsoleType']") - and _option_names(node.value) + and option_names(node.value) ] enabled = [ (key, value) for key, value in zip(base.value.keys, base.value.values) @@ -89,7 +89,7 @@ def melonds(cg: Configgen) -> list[Launcher]: ] if len(console) != 1 or len(enabled) != 1: src.fail("generate no longer sets Emu.ConsoleType from an option with external BIOS on") - option = _option_names(console[0].value)[0] + option = option_names(console[0].value)[0] enabled_key, enabled_value = enabled[0] if enabled_key is None: src.fail("base_config unpacks the section that enables the external BIOS") @@ -169,7 +169,7 @@ def gsplus(cg: Configgen) -> list[Launcher]: )] -def _system_branches(scope: ast.FunctionDef) -> list[tuple[str, ast.If]]: +def system_branches(scope: ast.FunctionDef) -> list[tuple[str, ast.If]]: """(system, branch) for each `if system.name == "":` of an if/elif chain.""" branches: list[tuple[str, ast.If]] = [] for node in ast.walk(scope): @@ -217,7 +217,7 @@ def _raised_fstring(node: ast.If) -> ast.JoinedStr | None: return None -def _render(message: ast.JoinedStr, var: str, value: str) -> str: +def render(message: ast.JoinedStr, var: str, value: str) -> str: parts = [] for part in message.values: if isinstance(part, ast.Constant): @@ -285,7 +285,7 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: prefix = cg.bios.rstrip("/") + "/" launchers = [] - for system, branch in _system_branches(generate): + for system, branch in system_branches(generate): bound = { assigned[0]: (stmt, assigned[1], _path_value(assigned[1], constants)) for stmt in branch.body if (assigned := assigned_value(stmt)) is not None @@ -317,7 +317,7 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: slot=system, names=[path[len(prefix):]], case_insensitive=False, search_dir=cg.bios, passes_to="exec", fails_when_missing=", ".join( - _render(message, binary, path) for message in (missing, not_executable) + render(message, binary, path) for message in (missing, not_executable) ), source_ref=src.ref(spans), )) diff --git a/scripts/scraper/batocera_searches.py b/scripts/scraper/batocera_searches.py index 9d88a9f55..63ca7a866 100644 --- a/scripts/scraper/batocera_searches.py +++ b/scripts/scraper/batocera_searches.py @@ -21,7 +21,7 @@ from .configgen_launchers import ( LANGUAGE_PLACEHOLDER = "L" -def _option_names(node: ast.AST) -> list[str]: +def option_names(node: ast.AST) -> list[str]: """Options a node reads: system.config.get*(o), system.config[o], system.isOptSet(o).""" found: list[str] = [] for child in ast.walk(node): @@ -395,7 +395,7 @@ def hatari(cg: Configgen) -> list[Launcher]: src.fail("findBestTos is not given a batoceraPaths directory") search_dir = cg.paths[call.args[0].id] kept = _trace(body, index) - options = list(dict.fromkeys(name for stmt in kept for name in _option_names(stmt))) + options = list(dict.fromkeys(name for stmt in kept for name in option_names(stmt))) spans = [src.span(stmt) for stmt in kept] + [(finder.lineno, end_line(finder))] second = call.args[1] if len(call.args) > 1 else None args = _tos_command_args( diff --git a/scripts/scraper/emuelec_launchers.py b/scripts/scraper/emuelec_launchers.py index 7f82602e8..fa2e58fb2 100644 --- a/scripts/scraper/emuelec_launchers.py +++ b/scripts/scraper/emuelec_launchers.py @@ -40,16 +40,16 @@ from .emuelec_runs import ( Runs, SX05RE, UTILS, - _ADVMAME_INSTALL, - _evidence, - _read, - _under, + ADVMAME_INSTALL, + evidence, + read, + under, ) def retroarch(tree: RepoTree, runs: Runs) -> list[Launcher]: """system_directory, written by sed into the retroarch.cfg the package installs.""" - mk = _read(tree, RETROARCH_MK) + mk = read(tree, RETROARCH_MK) sed_line, sed = mk.find( r"s/# system_directory =/system_directory =((?:\\/|[^/])+)/", "system_directory sed" ) @@ -99,7 +99,7 @@ def freej2me(tree: RepoTree, runs: Runs) -> list[Launcher]: export_line, _ = script.find(rf"^\s*export {java.group(1)}\s*$", "export", java_line) core = test.group(1) path = f"{LIBRETRO}/{core}/scripts/{call.group(1)}" - started = _read(tree, path) + started = read(tree, path) guard_line, guard = started.find(r'if \[\[ -f "([^"]+)" \]\]; then$', "JDK version test") copy_line, copy = started.find(r"^\s*cp -rf (\S+) (\S+)$", "jar copy", guard_line) source = copy.group(1) @@ -133,7 +133,7 @@ def freej2me(tree: RepoTree, runs: Runs) -> list[Launcher]: def pico8(tree: RepoTree, runs: Runs) -> list[Launcher]: """The folder the user drops in bios/ is moved where the binary runs from.""" path = f"{BIN}/pico8.sh" - script = _read(tree, path) + script = read(tree, path) guard_line, guard = script.find(r'if \[\[ -e "([^"]+)" \]\]; then$', "new version test") folder = guard.group(1) copy_line, copy = script.find( @@ -199,7 +199,7 @@ LINK_PACKAGES = ( def links(tree: RepoTree, runs: Runs) -> list[Launcher]: records = [] for path in LINK_SCRIPTS: - script = _read(tree, path) + script = read(tree, path) found = script.links(BIOS_ROOT) if not found: raise script.missing(f"ln -s of a path under {BIOS_ROOT}") @@ -209,7 +209,7 @@ def links(tree: RepoTree, runs: Runs) -> list[Launcher]: record.source_ref = f"{source_ref([runs.ref(name)])}, {record.source_ref}" records.append(record) for package in LINK_PACKAGES: - script = _read(tree, f"{package}/package.mk") + script = read(tree, f"{package}/package.mk") found = script.links(BIOS_ROOT, fixed={"INSTALL": ""}) if not found: raise script.missing(f"ln -s of a path under {BIOS_ROOT}") @@ -231,14 +231,14 @@ def duckstation(tree: RepoTree, runs: Runs) -> list[Launcher]: set_files = [k for k in file_keys if k in found and found[k].value] if set_files: raise LauncherPatternMissing(path, f"empty [BIOS] {set_files[0][1]}") - mk = _read(tree, f"{package}/package.mk") + mk = read(tree, f"{package}/package.mk") mk_line, _ = mk.find(r"cp -rf \$\{PKG_DIR\}/config/\* ", "config install") - script = _read(tree, f"{package}/scripts/duckstation.sh") + script = read(tree, f"{package}/scripts/duckstation.sh") run_line, _ = script.find(r'-settings "\$\{CONFIG_DIR\}/settings\.ini"', "-settings") name = posixpath.basename(script.path) lines = {found[k].line for k in (folder_key, *file_keys) if k in found} unset = describe_keys("", file_keys).strip() - return [_evidence( + return [evidence( Launcher( emulator=runs.emulator(name), build="standalone", @@ -268,7 +268,7 @@ def yabasanshiro(tree: RepoTree, runs: Runs) -> list[Launcher]: """The BIOS flag, set when the HLE option is off and the file exists.""" records = [] for path in YABASANSHIRO_SCRIPTS: - script = _read(tree, path) + script = read(tree, path) option_line, option = script.find(r"^\s*(\w+)=\$\(get_ee_setting (\w+) ", "HLE option") test_line, test = script.find( rf'if \[ "\$\{{{option.group(1)}\}}" != (\w+) \]', "HLE option test", option_line @@ -306,7 +306,7 @@ def yabasanshiro(tree: RepoTree, runs: Runs) -> list[Launcher]: def jzintv(tree: RepoTree, runs: Runs) -> list[Launcher]: path = f"{EMULATORS}/jzintv/scripts/jzintv.sh" - script = _read(tree, path) + script = read(tree, path) run_line, run = script.find(r"^\s*exec (\S+) .*\s(-p)\s+(\S+)\s", "start with -p") name = posixpath.basename(path) return [ @@ -325,7 +325,7 @@ def jzintv(tree: RepoTree, runs: Runs) -> list[Launcher]: def mupen64plus(tree: RepoTree, runs: Runs) -> list[Launcher]: """The 64DD IPL names, tried in order, passed only beside a .ndd disk.""" path = f"{EMULATORS}/mupen64plussa/mupen64plussa-core/m64p.sh" - script = _read(tree, path) + script = read(tree, path) fallbacks = [ (number, found) for number, line in script.code() @@ -377,7 +377,7 @@ def mupen64plus(tree: RepoTree, runs: Runs) -> list[Launcher]: def hatari(tree: RepoTree, runs: Runs) -> list[Launcher]: package = f"{EMULATORS}/hatarisa" - script = _read(tree, f"{package}/scripts/hatari.start") + script = read(tree, f"{package}/scripts/hatari.start") copy_line, copy = script.find(r'^\s*cp \S+/([\w.-]+\.cfg) "\$(\w+)"', "default config copy") run_lines = { n @@ -391,15 +391,15 @@ def hatari(tree: RepoTree, runs: Runs) -> list[Launcher]: keys = [ (s.section, s.key) for s in found - if _under(s.value) and "." in posixpath.basename(s.value) + if under(s.value) and "." in posixpath.basename(s.value) ] if not keys: raise LauncherPatternMissing(path, f"key naming a file under {BIOS_ROOT}") value, lines = fixed_paths(found, keys, path) - mk = _read(tree, f"{package}/package.mk") + mk = read(tree, f"{package}/package.mk") mk_line, _ = mk.find(r"cp -R \$\{PKG_DIR\}/config/\* ", "config install") name = posixpath.basename(script.path) - return [_evidence( + return [evidence( Launcher( emulator=runs.emulator(name), build="standalone", @@ -432,26 +432,26 @@ def advancemame(tree: RepoTree, runs: Runs) -> list[Launcher]: system reads its own record. """ package = f"{EMULATORS}/advancemame" - mk = _read(tree, f"{package}/package.mk") + mk = read(tree, f"{package}/package.mk") installs = [ (number, found.group(1)) for number, line in mk.code() - if (found := _ADVMAME_INSTALL.search(line)) + if (found := ADVMAME_INSTALL.search(line)) ] if not installs: raise mk.missing("advmame.rc install") by_value: dict[tuple[tuple[str, str], ...], list[tuple[str, set[int], int]]] = {} for mk_line, file in installs: path = f"{package}/config/{file}" - keys = [s for s in settings(tree.read(path), separator=" ") if _under(s.value, ROMS_ROOT)] - if not any(_under(s.value) for s in keys): + keys = [s for s in settings(tree.read(path), separator=" ") if under(s.value, ROMS_ROOT)] + if not any(under(s.value) for s in keys): raise LauncherPatternMissing(path, f"key naming a folder under {BIOS_ROOT}") value = tuple((s.key, s.value) for s in keys) by_value.setdefault(value, []).append((path, {s.line for s in keys}, mk_line)) if len(by_value) != 1: raise mk.missing("one set of BIOS folders for every device") ((value, configs),) = by_value.items() - script = _read(tree, f"{package}/bin/advmame.sh") + script = read(tree, f"{package}/bin/advmame.sh") run_line, _ = script.find(r"^\s*(?:\w+=\S+ )*advmame ", "advmame start") test_line, test = script.find(_ADVMAME_SYSTEM.pattern, "system test", end=run_line) sed_line, sed = script.find(_ADVMAME_SED.pattern, "system rewrite", test_line + 1, test_line + 1) @@ -468,7 +468,7 @@ def advancemame(tree: RepoTree, runs: Runs) -> list[Launcher]: target = script.expand("${CONFIG_DIR}/advmame.rc", run_line, set()) def proved(record: Launcher, key: str) -> Launcher: - return _evidence(record, script, target, [key], rewrites={sed_line}, tree=tree, + return evidence(record, script, target, [key], rewrites={sed_line}, tree=tree, installed=[(mk.path, {mk_line for _, _, mk_line in configs})]) records = [] @@ -499,7 +499,7 @@ def advancemame(tree: RepoTree, runs: Runs) -> list[Launcher]: def mame(tree: RepoTree, runs: Runs) -> list[Launcher]: """The files mame.sh copies into bios/mame, and the folders mame.ini hands the core.""" package = f"{LIBRETRO}/mame" - script = _read(tree, f"{package}/scripts/mame.sh") + script = read(tree, f"{package}/scripts/mame.sh") name = posixpath.basename(script.path) emulator = runs.emulator(name) records = [] @@ -513,7 +513,7 @@ def mame(tree: RepoTree, runs: Runs) -> list[Launcher]: continue if guard is None: raise script.missing(f"test before the copy at line {number}") - if not _under(copy.group(3)): + if not under(copy.group(3)): continue records.append( Launcher( @@ -541,7 +541,7 @@ def mame(tree: RepoTree, runs: Runs) -> list[Launcher]: def scummvm(tree: RepoTree, runs: Runs) -> list[Launcher]: """--extrapath for the standalone build, and the scummvm.ini copied for the core.""" path = f"{EMULATORS}/scummvmsa/bin/scummvm.start" - script = _read(tree, path) + script = read(tree, path) name = posixpath.basename(path) test_line, test = script.find(r'^\s*if \[ -d "([^"]+)" \]; then\s*$', "extra folder test") set_line, set_ = script.find(r'^\s*(\w+)="(--[\w-]+)=([^"]+)"', "extra path", test_line) @@ -562,7 +562,7 @@ def scummvm(tree: RepoTree, runs: Runs) -> list[Launcher]: used = {copy_line} source = script.expand(copy.group(1), copy_line, used) target = script.expand(copy.group(2), copy_line, used) - if not _under(target): + if not under(target): raise script.missing(f"copy into {BIOS_ROOT}") return [ Launcher( @@ -591,7 +591,7 @@ def scummvm(tree: RepoTree, runs: Runs) -> list[Launcher]: def dolphin(tree: RepoTree, runs: Runs) -> list[Launcher]: path = f"{EMULATORS}/dolphinSA/scripts/dolphin.sh" - script = _read(tree, path) + script = read(tree, path) run_line, run = script.find(r"\b(XDG_DATA_HOME)=(\S+) .*\bdolphin-emu", "XDG_DATA_HOME start") name = posixpath.basename(path) return [ @@ -616,7 +616,7 @@ def midi(tree: RepoTree, runs: Runs) -> list[Launcher]: call_line, _ = script.find( rf'set_midi_source "\$\{{{setting.group(1)}\}}"', "set_midi_source call", setting_line ) - utils = _read(tree, UTILS) + utils = read(tree, UTILS) head_line, _ = utils.find(r"^\s*function set_midi_source\(\)", "set_midi_source") end_line, _ = utils.find(r"^\s*esac\b", "end of the source case", head_line) records = [] @@ -636,7 +636,7 @@ def midi(tree: RepoTree, runs: Runs) -> list[Launcher]: if not paths or arm is None: continue ((flag, value),) = paths - is_file = "." in posixpath.basename(value) and _under(value) + is_file = "." in posixpath.basename(value) and under(value) records.append( Launcher( emulator=command[0], diff --git a/scripts/scraper/emuelec_runs.py b/scripts/scraper/emuelec_runs.py index 067cd59e9..484e85c60 100644 --- a/scripts/scraper/emuelec_runs.py +++ b/scripts/scraper/emuelec_runs.py @@ -38,7 +38,7 @@ _EMU_TEST = re.compile(r'\$\{?EMU\}?"?\s*==?\s*"([^"]+)"') _ARM = re.compile(r'^\s*((?:"[^"]+"\|?)+)\)\s*$') _RUNTHIS = re.compile(r"""^\s*RUNTHIS\+?=(['"])(.*)\1\s*$""") _SCRIPT = re.compile(r"[\w./-]+\.(?:sh|start)$") -_ADVMAME_INSTALL = re.compile(r"cp -r \$\{PKG_DIR\}/config/(advmame\.rc\w*) \S+/advmame\.rc$") +ADVMAME_INSTALL = re.compile(r"cp -r \$\{PKG_DIR\}/config/(advmame\.rc\w*) \S+/advmame\.rc$") @dataclass @@ -108,14 +108,14 @@ def _storage_path(tree: RepoTree, target: str) -> str: The emuelec package links /emuelec to /storage/.config/emuelec, where the first-boot copy of /usr/config lands. """ - mk = _read(tree, EMUELEC_MK) + mk = read(tree, EMUELEC_MK) _line, link = mk.find(r"ln -sf (/storage/\S+) \$\{INSTALL\}(/emuelec)$", "/emuelec link") if target == link.group(2) or target.startswith(link.group(2) + "/"): return link.group(1) + target[len(link.group(2)):] return target -def _evidence( +def evidence( record: Launcher, script: Script, target: str, @@ -135,7 +135,7 @@ def _evidence( """ placements = [] if tree is not None: - placements.append(first_boot_placement(_read(tree, USERCONFIG), _storage_path(tree, target))) + placements.append(first_boot_placement(read(tree, USERCONFIG), _storage_path(tree, target))) placement = config_placement(script, target, keys, source_name=source_name, required=not placements or not placements[0].install) placement.overrides |= set(rewrites) @@ -143,9 +143,9 @@ def _evidence( return apply_evidence(record, placements, installed) -def _read(tree: RepoTree, path: str) -> Script: +def read(tree: RepoTree, path: str) -> Script: return Script(path, tree.read(path)) -def _under(path: str, root: str = BIOS_ROOT) -> bool: +def under(path: str, root: str = BIOS_ROOT) -> bool: return path.rstrip("/") == root or path.startswith(root + "/") diff --git a/scripts/scraper/knulli_launchers.py b/scripts/scraper/knulli_launchers.py index ea0f3393e..776848da2 100644 --- a/scripts/scraper/knulli_launchers.py +++ b/scripts/scraper/knulli_launchers.py @@ -37,7 +37,7 @@ from .batocera_launchers import ( patched_paths, working_directories, ) -from .batocera_config_writes import _render, _system_branches, melonds, mupen64plus, x16emu, xemu +from .batocera_config_writes import render, system_branches, melonds, mupen64plus, x16emu, xemu from .batocera_searches import duckstation, duckstation_legacy, hatari from .batocera_configgen import Configgen, _path_value from .configgen_launchers import ( @@ -151,7 +151,7 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: src.fail(f"expected one command line starting with {binary}, found {len(commands)}") prefix = cg.bios.rstrip("/") + "/" launchers = [] - for system, branch in _system_branches(generate): + for system, branch in system_branches(generate): bound = [ (stmt, held) for stmt in branch.body if _assigned_name(stmt) == binary and isinstance((held := _bound(stmt)), ast.Name) @@ -163,7 +163,7 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: path = constants.get(constant) if path is None or not path.startswith(prefix): src.fail(f"{constant} is not a path under {cg.bios}") - messages = [_render(m, binary, path) for m in (missing_message, access_message)] + messages = [render(m, binary, path) for m in (missing_message, access_message)] launchers.append(Launcher( emulator=cg.emulator(module), build="standalone", kind="fixed_name", slot=system, names=[path[len(prefix):]], case_insensitive=False, diff --git a/scripts/scraper/recalbox_cascades.py b/scripts/scraper/recalbox_cascades.py index bceee89bf..cde2ede32 100644 --- a/scripts/scraper/recalbox_cascades.py +++ b/scripts/scraper/recalbox_cascades.py @@ -23,11 +23,11 @@ from .recalbox_configgen import ( GSPLUS, HATARI, TOS_FUNCTIONS, - _assignments, - _expr_call, - _setter, - _string, - _text, + assignments, + expr_call, + is_setter_call, + string, + string_constant, spell, ) @@ -77,7 +77,7 @@ def _tos_setter( ) -> tuple[ast.Call, str, str]: """The setting written from str(), the path variable, and where it goes.""" paths = { - name for _node, name, value in _assignments(ast.walk(scope)) + name for _node, name, value in assignments(ast.walk(scope)) if isinstance(value, ast.Call) and ast.unparse(value.func) == "os.path.join" } setters = [ @@ -168,7 +168,7 @@ def _rom_override(src: Source, stmt: ast.If, var: str) -> tuple[str, ast.expr] | and len(stmt.body) == 1 ): return None - marker = _text(src, stmt.test.left, "rom path marker") + marker = string_constant(src, stmt.test.left, "rom path marker") value = _assigns(stmt.body[0], var) return None if marker is None or value is None else (marker, value) @@ -220,7 +220,7 @@ def _machine_depends(src: Source, scope: ast.FunctionDef, table: ast.stmt) -> st } options = [ option for call in _calls(scope, attr="getInt") - if call.args and (option := _text(src, call.args[0], "machine option")) is not None + if call.args and (option := string_constant(src, call.args[0], "machine option")) is not None and isinstance(call.func, ast.Attribute) and isinstance(call.func.value, ast.Name) and call.func.value.id in bound ] @@ -274,7 +274,7 @@ def tos_cascade(cg: Configgen, src: Source, scope: ast.FunctionDef, emulator: st n.id for stmt in body[index:body.index(setter_stmt) + 1] for n in ast.walk(stmt) if isinstance(n, ast.Name) } - helpers = [src.span(node) for node, name, value in _assignments(scope.body) + helpers = [src.span(node) for node, name, value in assignments(scope.body) if name in read - {var} and spell(value, env) is not None] ref = src.ref([ (min(machine_lines), max(machine_lines)), @@ -348,7 +348,7 @@ def _gsplus_tries( isinstance(test, ast.If) and var is not None and exists_of(test.test, var) ): src.fail(f"line {stmts[i].lineno}: path is not tried with os.path.exists") - calls = [c for stmt in test.body if (c := _expr_call(stmt))] + calls = [c for stmt in test.body if (c := expr_call(stmt))] for c in calls: if not isinstance(c.func, ast.Attribute): src.fail(f"line {c.lineno}: a call of the found branch is not a method call") @@ -357,7 +357,7 @@ def _gsplus_tries( if isinstance(c.func, ast.Attribute) and c.func.attr == "setString" and ast.unparse(c.args[1]) == var ] - found = _string(written[0].args[0]) if len(written) == 1 else None + found = string(written[0].args[0]) if len(written) == 1 else None if found is None or (key is not None and found != key): src.fail(f"line {test.lineno}: the found path is not written to one key") key = found @@ -367,7 +367,7 @@ def _gsplus_tries( stmts, i = orelse, 0 continue removed = [ - c for stmt in orelse if (c := _expr_call(stmt)) and _setter(c, key, "removeOption") + c for stmt in orelse if (c := expr_call(stmt)) and is_setter_call(c, key, "removeOption") ] if len(orelse) != 1 or not removed: src.fail(f"line {test.lineno}: the last miss does not remove {key}") @@ -394,7 +394,7 @@ def gsplus(cg: Configgen) -> list[Launcher]: node for node in ast.walk(generate) if isinstance(node, ast.If) and any(child is body[index] for child in node.orelse) ) - marker = _string(guard.test.left) if isinstance(guard.test, ast.Compare) else None + marker = string(guard.test.left) if isinstance(guard.test, ast.Compare) else None if marker is None: src.fail("the BIOS search is not the else of a rom path test") launchers = [Launcher( @@ -408,13 +408,13 @@ def gsplus(cg: Configgen) -> list[Launcher]: isinstance(node, ast.If) and isinstance(node.test, ast.Compare) and isinstance(node.test.left, ast.Call) - and _setter(node.test.left, key, "getString") + and is_setter_call(node.test.left, key, "getString") ): continue - placeholder = _text(src, node.test.comparators[0], "placeholder") + placeholder = string_constant(src, node.test.comparators[0], "placeholder") if placeholder is None: continue - written = [c for stmt in node.body if (c := _expr_call(stmt)) and _setter(c, key)] + written = [c for stmt in node.body if (c := expr_call(stmt)) and is_setter_call(c, key)] name = cg.under_bios(spell(written[0].args[1], env)) if len(written) == 1 else None if name is None: src.fail(f"line {node.lineno}: placeholder branch writes no BIOS path") diff --git a/scripts/scraper/recalbox_configgen.py b/scripts/scraper/recalbox_configgen.py index 17e321e20..1b710e491 100644 --- a/scripts/scraper/recalbox_configgen.py +++ b/scripts/scraper/recalbox_configgen.py @@ -51,14 +51,14 @@ FILE_OPTIONS = {"o2em_bios": "o2em"} BUILTIN_TOKEN = re.compile(r"<[^<>/]+>") -def _string(node: ast.AST | None) -> str | None: +def string(node: ast.AST | None) -> str | None: """The value of a string constant.""" if isinstance(node, ast.Constant) and isinstance(node.value, str): return node.value return None -def _text(source: Source, node: ast.AST | None, what: str) -> str | None: +def string_constant(source: Source, node: ast.AST | None, what: str) -> str | None: """The value of a string constant, None for any other node. A constant that is not a string is a shape the reader does not know.""" if not isinstance(node, ast.Constant): @@ -68,7 +68,7 @@ def _text(source: Source, node: ast.AST | None, what: str) -> str | None: return node.value -def _assignments( +def assignments( nodes: Iterable[ast.AST], ) -> Iterator[tuple[ast.Assign | ast.AnnAssign, str, ast.expr]]: """Each single-name assignment among `nodes`, its name and its value.""" @@ -116,14 +116,14 @@ def spell(node: ast.AST | None, env: Mapping[str, str]) -> str | None: def module_strings(source: Source, prefix: str) -> dict[str, str]: """Module-level string constants, keyed as `prefix.NAME`.""" local: dict[str, str] = {} - for _node, name, expr in _assignments(source.tree.body): + for _node, name, expr in assignments(source.tree.body): value = spell(expr, local) if value is not None: local[name] = value return {f"{prefix}.{name}": value for name, value in local.items()} -def _class_strings(source: Source, env: dict[str, str]) -> dict[str, Any]: +def class_strings(source: Source, env: dict[str, str]) -> dict[str, Any]: """Class attributes readable as strings or as tuples of strings.""" found: dict[str, Any] = {} for cls in source.tree.body: @@ -131,7 +131,7 @@ def _class_strings(source: Source, env: dict[str, str]) -> dict[str, Any]: continue # The class body reads its own attributes by their bare names. bare: dict[str, str] = {} - for _node, name, expr in _assignments(cls.body): + for _node, name, expr in assignments(cls.body): scope = {**env, **found, **bare} value: Any = spell(expr, scope) if value is None and isinstance(expr, ast.Tuple): @@ -149,7 +149,7 @@ def _class_strings(source: Source, env: dict[str, str]) -> dict[str, Any]: def _bound_once(scope: ast.AST, env: dict[str, str]) -> dict[str, str]: """Names a function binds exactly once to a readable string.""" counts: dict[str, int] = {} - found = list(_assignments(ast.walk(scope))) + found = list(assignments(ast.walk(scope))) for _node, name, _expr in found: counts[name] = counts.get(name, 0) + 1 local: dict[str, str] = {} @@ -171,11 +171,11 @@ def launcher_names(source: Source) -> dict[str, list[str]]: and isinstance(node.test.ops[0], ast.Eq) ): continue - emulator = _text(source, node.test.comparators[0], "emulator name") + emulator = string_constant(source, node.test.comparators[0], "emulator name") if emulator is None: continue for call in _calls(ast.Module(body=node.body, type_ignores=[]), name="__import__"): - module = _text(source, call.args[0], "generator module") if call.args else None + module = string_constant(source, call.args[0], "generator module") if call.args else None if module is not None: names.setdefault(module, []).append(emulator) if not names: @@ -183,14 +183,14 @@ def launcher_names(source: Source) -> dict[str, list[str]]: return names -def _handler_map(source: Source, function: str, table: str) -> dict[str, list[str]]: +def handler_map(source: Source, function: str, table: str) -> dict[str, list[str]]: """Function name -> the keys a dispatch table of `function` sends to it.""" node = source.assignment(table, source.function(function)).value if not isinstance(node, ast.Dict): source.fail(f"{table} is not a dict display") handlers: dict[str, list[str]] = {} for key, value in zip(node.keys, node.values): - name = _text(source, key, f"{table} key") + name = string_constant(source, key, f"{table} key") if name is not None and isinstance(value, ast.Attribute): handlers.setdefault(value.attr, []).append(name) if not handlers: @@ -226,7 +226,7 @@ class Configgen: def core(self, function: str) -> str: """The libretro cores fillCoresConfiguration hands to `function`.""" - cores = _handler_map(self.source(CORES), "fillCoresConfiguration", "specificCoreHandlers") + cores = handler_map(self.source(CORES), "fillCoresConfiguration", "specificCoreHandlers") if function not in cores: self.source(CORES).fail(f"no core is configured by {function}") return join_emulators(cores[function]) @@ -235,7 +235,7 @@ class Configgen: """recalboxFiles, the module's class attributes and the strings `scope` binds once, with the system name left as a placeholder.""" env: dict[str, Any] = dict(self.files) - env.update(_class_strings(source, env)) + env.update(class_strings(source, env)) env.update({name: SYSTEM_PLACEHOLDER for name in SYSTEM_NAMES}) if scope is not None: env.update(_bound_once(scope, env)) @@ -255,7 +255,7 @@ class Configgen: return value.rstrip("/") -def _setter(call: ast.Call, key: str, attr: str = "setString") -> bool: +def is_setter_call(call: ast.Call, key: str, attr: str = "setString") -> bool: return ( isinstance(call.func, ast.Attribute) and call.func.attr == attr @@ -265,18 +265,18 @@ def _setter(call: ast.Call, key: str, attr: str = "setString") -> bool: ) -def _expr_call(stmt: ast.stmt) -> ast.Call | None: +def expr_call(stmt: ast.stmt) -> ast.Call | None: if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call): return stmt.value return None -def _systems( +def accepted_systems( source: Source, test: ast.expr, lists: Mapping[str, list[str]] ) -> list[str] | None: """The systems a `system.Name == x`, `or` or `in list` test accepts.""" if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or): - parts = [_systems(source, value, lists) for value in test.values] + parts = [accepted_systems(source, value, lists) for value in test.values] systems: list[str] = [] for part in parts: if part is None: @@ -289,7 +289,7 @@ def _systems( and ast.unparse(test.left) in SYSTEM_NAMES ): right = test.comparators[0] - system = _text(source, right, "system name") + system = string_constant(source, right, "system name") if isinstance(test.ops[0], ast.Eq) and system is not None: return [system] if isinstance(test.ops[0], ast.In) and isinstance(right, ast.Name) and right.id in lists: @@ -310,7 +310,7 @@ def _condition(source: Source, tests: list[ast.expr], negated: bool, systems: list[str] = [] flags: list[str] = [] for test in tests: - found = _systems(source, test, lists) + found = accepted_systems(source, test, lists) flag = _flag(test) if found is not None: systems += found @@ -337,18 +337,18 @@ def _else_line(source: Source, first: ast.stmt) -> int: return line if line > 0 else first.lineno -def _setter_branches( +def setter_branches( source: Source, stmts: list[ast.stmt], key: str, lists: Mapping[str, list[str]] ) -> list[tuple[str | None, ast.Call, int]]: """(condition, setter call, first line) for each branch writing `key`.""" found: list[tuple[str | None, ast.Call, int]] = [] for stmt in stmts: - call = _expr_call(stmt) - if call is not None and _setter(call, key): + call = expr_call(stmt) + if call is not None and is_setter_call(call, key): found.append((None, call, stmt.lineno)) continue if not isinstance(stmt, ast.If): - if any(_setter(c, key) for c in _calls(stmt, attr="setString")): + if any(is_setter_call(c, key) for c in _calls(stmt, attr="setString")): source.fail(f"line {stmt.lineno}: {key} is written outside an if chain") continue node, tests = stmt, [] @@ -370,19 +370,19 @@ def _setter_branches( def _branch( source: Source, stmts: list[ast.stmt], key: str, condition: str, start: int ) -> list[tuple[str | None, ast.Call, int]]: - calls = [c for stmt in stmts if (c := _expr_call(stmt)) is not None and _setter(c, key)] - nested = [c for stmt in stmts for c in _calls(stmt, attr="setString") if _setter(c, key)] + calls = [c for stmt in stmts if (c := expr_call(stmt)) is not None and is_setter_call(c, key)] + nested = [c for stmt in stmts for c in _calls(stmt, attr="setString") if is_setter_call(c, key)] if len(calls) != len(nested) or len(calls) > 1: source.fail(f"line {start}: {key} is written in a nested branch") return [(condition, call, start) for call in calls] -def _local_lists(source: Source, scope: ast.AST) -> dict[str, tuple[list[str], ast.stmt]]: +def local_string_lists(source: Source, scope: ast.AST) -> dict[str, tuple[list[str], ast.stmt]]: found: dict[str, tuple[list[str], ast.stmt]] = {} - for node, name, value in _assignments(ast.walk(scope)): + for node, name, value in assignments(ast.walk(scope)): if isinstance(value, ast.List): values = [text for e in value.elts - if (text := _text(source, e, f"{name} item")) is not None] + if (text := string_constant(source, e, f"{name} item")) is not None] if len(values) == len(value.elts): found[name] = (values, node) return found diff --git a/scripts/scraper/recalbox_emulators.py b/scripts/scraper/recalbox_emulators.py index f8acb2858..44dace19e 100644 --- a/scripts/scraper/recalbox_emulators.py +++ b/scripts/scraper/recalbox_emulators.py @@ -30,13 +30,13 @@ from .recalbox_configgen import ( SYSTEM_PLACEHOLDER, XEMU, XROAR, - _assignments, - _class_strings, - _expr_call, - _setter, - _string, - _systems, - _text, + assignments, + class_strings, + expr_call, + is_setter_call, + string, + accepted_systems, + string_constant, spell, ) @@ -44,7 +44,7 @@ from .recalbox_configgen import ( def amiberry(cg: Configgen) -> list[Launcher]: """BIOS_PER_SYSTEM tried in order, the AROS pair, then Amiberry's own.""" kick = cg.source(AMIBERRY_KICKSTARTS) - subsystems = _class_strings(cg.source(AMIBERRY_SUBSYSTEMS), {}) + subsystems = class_strings(cg.source(AMIBERRY_SUBSYSTEMS), {}) computers = subsystems.get("SubSystems.COMPUTERS") if not isinstance(computers, list): cg.source(AMIBERRY_SUBSYSTEMS).fail("SubSystems.COMPUTERS is not a tuple of systems") @@ -72,23 +72,23 @@ def amiberry(cg: Configgen) -> list[Launcher]: message for node in ast.walk(chooser) if isinstance(node, ast.Raise) and isinstance(node.exc, ast.Call) and node.exc.args - and (message := _text(kick, node.exc.args[0], "failure message")) is not None + and (message := string_constant(kick, node.exc.args[0], "failure message")) is not None ] aros = [ aros_name for call in _calls(chooser, name="AmigaBios") - if call.args and (aros_name := _text(kick, call.args[0], "AROS name")) is not None + if call.args and (aros_name := string_constant(kick, call.args[0], "AROS name")) is not None ] builtin = [ rom for node in ast.walk(chooser) if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "self.rom" - and (rom := _text(kick, node.value, "built-in rom")) is not None + and (rom := string_constant(kick, node.value, "built-in rom")) is not None ] if len(messages) != 2 or len(aros) != 2 or len(builtin) != 1: kick.fail("GetKickstartsFor no longer has two failures, the AROS pair and a built-in") config = cg.source(AMIBERRY_CONFIG) setter = config.function("SetKickstarts") keys = [setting for c in _calls(setter, attr="setString") - if (setting := _text(config, c.args[0], "kickstart key")) is not None] + if (setting := string_constant(config, c.args[0], "kickstart key")) is not None] if len(keys) != 2: config.fail("SetKickstarts no longer writes a kickstart and an extended ROM") rom_key, ext_key = keys @@ -139,7 +139,7 @@ def _amiberry_rom_path(cg: Configgen, emulator: str) -> Launcher: """amiberry.conf rom_path, the folder Amiberry scans for every ROM.""" src = cg.source(AMIBERRY_GLOBAL) create = src.function("createGlobalSettings") - found = [c for c in _calls(create, attr="setString") if _setter(c, "rom_path")] + found = [c for c in _calls(create, attr="setString") if is_setter_call(c, "rom_path")] if len(found) != 1 or len(found[0].args) != 2: src.fail(f"expected one rom_path setter, found {len(found)}") call = found[0] @@ -178,7 +178,7 @@ def _region_branch(node: ast.If, helper: str) -> tuple[str, ast.expr, ast.expr | ): return None compare, call = test.values - token = _string(compare.left) if isinstance(compare, ast.Compare) else None + token = string(compare.left) if isinstance(compare, ast.Compare) else None if not ( token is not None and isinstance(call, ast.Call) @@ -241,7 +241,7 @@ def pcsx2(cg: Configgen) -> list[Launcher]: src.fail("the chosen BIOS is not written to one config key") constants = {v: k.removeprefix("self.").removeprefix("Pcsx2Generator.") for k, v in env.items() if k.startswith("Pcsx2Generator.BIOS_")} - names_lines = [node.lineno for node, name, _value in _assignments(ast.walk(src.tree)) + names_lines = [node.lineno for node, name, _value in assignments(ast.walk(src.tree)) if name in set(constants.values())] ref = src.ref([(min(names_lines), max(names_lines)), (chooser.lineno, end_line(chooser)), (writes[0].lineno, end_line(writes[0]))]) @@ -290,7 +290,7 @@ def _presence(cg: Configgen, src: Source, scope: ast.FunctionDef) -> tuple[list[ def _returned(stmts: list[ast.stmt]) -> str | None: if len(stmts) == 1 and isinstance(stmts[0], ast.Return): - return _string(stmts[0].value) + return string(stmts[0].value) return None @@ -307,14 +307,14 @@ def dolphin(cg: Configgen) -> list[Launcher]: and any( name == bound.id and isinstance(value, ast.Call) and isinstance(value.func, ast.Attribute) and value.func.attr == checker.name - for _node, name, value in _assignments(ast.walk(src.tree)) + for _node, name, value in assignments(ast.walk(src.tree)) ) ] if found is None or missing is None or len(calls) != 1: src.fail("CheckGamecubeIpl's answer is not written to one config key") call, answer = calls[0] section, key = spell(call.args[0], env), spell(call.args[1], env) - binding = next(node for node, name, _value in _assignments(ast.walk(src.tree)) + binding = next(node for node, name, _value in assignments(ast.walk(src.tree)) if name == answer) standalone = Launcher( emulator=cg.emulator(DOLPHIN), build="standalone", kind="fixed_name", names=names, @@ -328,14 +328,14 @@ def dolphin(cg: Configgen) -> list[Launcher]: configure = cores.function("configureDolphin") names, test = _presence(cg, cores, configure) options = [(option, value) for branch in (test.body, test.orelse) - for stmt in branch if (c := _expr_call(stmt)) and len(c.args) == 2 - and (option := _text(cores, c.args[0], "core option")) is not None - and (value := _text(cores, c.args[1], "core option value")) is not None] + for stmt in branch if (c := expr_call(stmt)) and len(c.args) == 2 + and (option := string_constant(cores, c.args[0], "core option")) is not None + and (value := string_constant(cores, c.args[1], "core option value")) is not None] if len(options) != 2 or options[0][0] != options[1][0]: cores.fail("configureDolphin's presence test does not set one core option both ways") option = options[0][0] on, off = (value.strip('"') for _o, value in options) - first = min(node.lineno for node, _name, value in _assignments(ast.walk(configure)) + first = min(node.lineno for node, _name, value in assignments(ast.walk(configure)) if cg.under_bios(spell(value, cg.env(cores, configure))) is not None) libretro = Launcher( emulator=cg.core("configureDolphin"), build="libretro", kind="fixed_name", names=names, @@ -371,7 +371,7 @@ def _config_paths(cg: Configgen, path: str, emulator: str) -> Launcher: ) if test is not None: spans.append((test.lineno, test.lineno)) - systems = _systems(src, test.test, {}) + systems = accepted_systems(src, test.test, {}) words = f"system {', '.join(systems)}" if systems else _enclosing_test(function, call) if words is not None and words not in conditions: conditions.append(words) diff --git a/scripts/scraper/recalbox_launchers.py b/scripts/scraper/recalbox_launchers.py index 80b31d39e..e6a2f799e 100644 --- a/scripts/scraper/recalbox_launchers.py +++ b/scripts/scraper/recalbox_launchers.py @@ -50,13 +50,13 @@ from .recalbox_configgen import ( SYSTEM_DIRECTORY, XEMU, XROAR, - _expr_call, - _handler_map, - _local_lists, - _setter, - _setter_branches, - _string, - _text, + expr_call, + handler_map, + local_string_lists, + is_setter_call, + setter_branches, + string, + string_constant, spell, ) from .recalbox_emulators import amiberry, dolphin, mupen64plus, pcsx2, xemu, xroar @@ -76,7 +76,7 @@ def system_directories(cg: Configgen) -> list[Launcher]: node for node in ast.walk(src.tree) if isinstance(node, ast.Match) and ast.unparse(node.subject) == "self.system.Core" - and any(_setter(c, SYSTEM_DIRECTORY) for c in _calls(node, attr="setString")) + and any(is_setter_call(c, SYSTEM_DIRECTORY) for c in _calls(node, attr="setString")) ] if len(matches) != 1: src.fail(f"expected one match on the core writing {SYSTEM_DIRECTORY}, " @@ -84,7 +84,7 @@ def system_directories(cg: Configgen) -> list[Launcher]: match = matches[0] scope = _innermost_function(src, match) env = cg.env(src, scope) - local_lists = _local_lists(src, scope) + local_lists = local_string_lists(src, scope) lists = {name: values for name, (values, _node) in local_lists.items()} def record(emulator: str, condition: str | None, call: ast.Call, @@ -104,11 +104,11 @@ def system_directories(cg: Configgen) -> list[Launcher]: options = pattern.patterns if isinstance(pattern, ast.MatchOr) else [pattern] cores = [core for p in options if isinstance(p, ast.MatchValue) - and (core := _text(src, p.value, "core name")) is not None] + and (core := string_constant(src, p.value, "core name")) is not None] wildcard = isinstance(pattern, ast.MatchAs) and pattern.pattern is None if not wildcard and len(cores) != len(options): src.fail(f"line {pattern.lineno}: case pattern is not a list of core names") - branches = _setter_branches(src, case.body, SYSTEM_DIRECTORY, lists) + branches = setter_branches(src, case.body, SYSTEM_DIRECTORY, lists) if not branches: src.fail(f"line {pattern.lineno}: case writes no {SYSTEM_DIRECTORY}") for condition, call, start in branches: @@ -124,7 +124,7 @@ def system_directories(cg: Configgen) -> list[Launcher]: if located is None: src.fail(f"no statement list holds the match on the core writing {SYSTEM_DIRECTORY}") body, index = located - overrides = _setter_branches(src, body[index + 1:], SYSTEM_DIRECTORY, lists) + overrides = setter_branches(src, body[index + 1:], SYSTEM_DIRECTORY, lists) if not overrides: src.fail(f"no per-system {SYSTEM_DIRECTORY} after the match on the core") tests = {node.lineno: node.test for node in ast.walk(scope) if isinstance(node, ast.If)} @@ -166,10 +166,10 @@ def core_assets(cg: Configgen) -> list[Launcher]: and isinstance(node.test.ops[0], ast.Eq) ): continue - core = _text(src, node.test.comparators[0], "core name") + core = string_constant(src, node.test.comparators[0], "core name") if core is None: continue - calls = [c for stmt in node.body if (c := _expr_call(stmt)) and _setter(c, CORE_ASSETS)] + calls = [c for stmt in node.body if (c := expr_call(stmt)) and is_setter_call(c, CORE_ASSETS)] if len(calls) != 1: continue call = calls[0] @@ -197,7 +197,7 @@ def content_files(cg: Configgen) -> list[Launcher]: and ast.unparse(node.test.left) == "core" ): continue - core = _text(src, node.test.comparators[0], "core name") + core = string_constant(src, node.test.comparators[0], "core name") if core is None: continue refs = [n for n in ast.walk(node) if isinstance(n, ast.Attribute) @@ -231,7 +231,7 @@ def content_files(cg: Configgen) -> list[Launcher]: def core_file_options(cg: Configgen, directories: list[Launcher]) -> list[Launcher]: """System handlers that set a core option naming the file the core opens.""" src = cg.source(CORES) - handlers = _handler_map(src, "fillCoresConfiguration", "specificSystemHandlers") + handlers = handler_map(src, "fillCoresConfiguration", "specificSystemHandlers") table = src.assignment( "specificSystemHandlers", src.function("fillCoresConfiguration") ).value @@ -245,10 +245,10 @@ def core_file_options(cg: Configgen, directories: list[Launcher]) -> list[Launch continue for call in _calls(function, attr="setString"): if not (len(call.args) == 2 and all(isinstance(a, ast.Constant) for a in call.args) - and _string(call.args[0]) in FILE_OPTIONS): + and string(call.args[0]) in FILE_OPTIONS): continue - option = _text(src, call.args[0], "core option") - value = _text(src, call.args[1], "core option value") + option = string_constant(src, call.args[0], "core option") + value = string_constant(src, call.args[1], "core option value") if option is None or value is None: continue core = FILE_OPTIONS[option] diff --git a/scripts/scraper/retrobat_arguments.py b/scripts/scraper/retrobat_arguments.py index 19acb6553..94c725628 100644 --- a/scripts/scraper/retrobat_arguments.py +++ b/scripts/scraper/retrobat_arguments.py @@ -16,8 +16,8 @@ from .csharp_source import ( _unescape, source_ref, ) -from .retrobat_generators import FEATURES, GENERATORS, _record, system_feature_choices -from .retrobat_render import _covered, _path_parts, _render, _when +from .retrobat_generators import FEATURES, GENERATORS, launcher_record, system_feature_choices +from .retrobat_render import covered_records, path_parts, render, when def _argument_paths(src: Source, emulator: str, build: str) -> list[tuple[Record, list[str]]]: @@ -30,22 +30,22 @@ def _argument_paths(src: Source, emulator: str, build: str) -> list[tuple[Record if re.fullmatch(STRING, expr.strip()): continue method = _method_of(src, add.start()) - rendered = _render(src, expr, method[0], add.start()) + rendered = render(src, expr, method[0], add.start()) if rendered is None or not rendered[0].startswith("bios"): continue flags = list(re.finditer(r'"(-[\w-]+)"', code[method[0] : add.start()])) if not flags: raise LauncherPatternMissing(src.path, f"flag before line {src.line(add.start())}") flag_at = method[0] + flags[-1].start() - conditions, returns = _when(src, add.start()) + conditions, returns = when(src, add.start()) found.append( ( - _record( + launcher_record( emulator, build, "passes_path", [], - _path_parts( + path_parts( src, *returns, *rendered[1], @@ -80,7 +80,7 @@ def mame(sources: dict[str, Source]) -> list[Record]: found = _argument_paths(own, "mame64", "standalone") if not found: raise LauncherPatternMissing(own.path, "MAME folder arguments") - records = _covered( + records = covered_records( own, [ split @@ -102,7 +102,7 @@ def mame(sources: dict[str, Source]) -> list[Record]: shared.append(_with_conditions(record, conditions)) libretro = dict(record, emulator="mame", build="libretro", names=[]) shared.append(_with_conditions(libretro, conditions)) - return records + _covered( + return records + covered_records( mess, shared, # The softlist file and the Lua autoboot script are named after the game. @@ -119,7 +119,7 @@ def psxmame(sources: dict[str, Source]) -> list[Record]: found = _argument_paths(src, "psxmame", "standalone") if not found: raise LauncherPatternMissing(src.path, "rompath argument") - return _covered(src, [_with_conditions(record, conditions) for record, conditions in found]) + return covered_records(src, [_with_conditions(record, conditions) for record, conditions in found]) def xroar(sources: dict[str, Source]) -> list[Record]: @@ -158,12 +158,12 @@ def xroar(sources: dict[str, Source]) -> list[Record]: if "bios" not in parts: raise LauncherPatternMissing(src.path, "bios in the config rompath") records.append( - _record( + launcher_record( "xroar", "standalone", "passes_path", [], - _path_parts( + path_parts( src, src.lines(line.start(), line.end()), src.lines(use.start(), use.end()) ), search_dir="/".join(parts[parts.index("bios") :]), @@ -171,7 +171,7 @@ def xroar(sources: dict[str, Source]) -> list[Record]: fails_when_missing=False, ) ) - return _covered(src, records) + return covered_records(src, records) _EMULATOR_BRANCH = re.compile(r"([^\s;<>]+) when (\w+), else ([^\s;<>]+)") @@ -205,7 +205,7 @@ def _per_emulator(src: Source, record: Record) -> list[Record]: for emulator, directory in ((declared.group(1), chosen), (record["emulator"], default)): split = {k: v for k, v in record.items() if k != "source_ref"} split.update(emulator=emulator, search_dir=directory, passes_to=f"{prefix} {directory}") - split["source_ref"] = _path_parts(src, *spans) + split["source_ref"] = path_parts(src, *spans) out.append(split) return out @@ -292,7 +292,7 @@ def portable_users(sources: dict[str, Source]) -> list[Record]: if alternate: spans.append(src.lines(alternate.start(), alternate.end())) depends = "unless saves/switch/ryujinx/portable exists, passed with -r" - records.append(_record( + records.append(launcher_record( emulator, "standalone", "passes_path", @@ -321,7 +321,7 @@ def pico8(sources: dict[str, Source]) -> list[Record]: check = src.find(r"if \(!File\.Exists\(exe\)\)\s*return null;", "binary check", exe.end()) run = src.find(r"FileName = exe,\s*WorkingDirectory = path,", "binary run", check.end()) return [ - _record( + launcher_record( "pico8", "standalone", "fixed_name", diff --git a/scripts/scraper/retrobat_computers.py b/scripts/scraper/retrobat_computers.py index e3cd5fcd6..e5eb8e580 100644 --- a/scripts/scraper/retrobat_computers.py +++ b/scripts/scraper/retrobat_computers.py @@ -18,8 +18,8 @@ from .retrobat_generators import ( FEATURES, GENERATORS, TARGET_ABSENT, - _joined, - _record, + joined, + launcher_record, feature_choices, ) @@ -73,7 +73,7 @@ def hatari(sources: dict[str, Source]) -> list[Record]: head = src.lines(folder.start(), emutos.end()) tail = src.lines(write.start(), write.end()) return [ - _record( + launcher_record( "hatari", "standalone", "fixed_name", @@ -85,7 +85,7 @@ def hatari(sources: dict[str, Source]) -> list[Record]: fails_when_missing=f"{tos_folder}/{emutos.group(2)} instead, else {message}", depends_on_option=f"{option} unset, no hard disk image", ), - _record( + launcher_record( "hatari", "standalone", "core_option", @@ -100,7 +100,7 @@ def hatari(sources: dict[str, Source]) -> list[Record]: fails_when_missing=message, depends_on_option=option, ), - _record( + launcher_record( "hatari", "standalone", "fixed_name", @@ -112,7 +112,7 @@ def hatari(sources: dict[str, Source]) -> list[Record]: fails_when_missing=f"{name} is used, as without a hard disk image", depends_on_option=f"{option} unset, a hard disk image mounted or no {name}", ), - _record( + launcher_record( "hatari", "standalone", "names_searched", @@ -145,7 +145,7 @@ def hatari_libretro(sources: dict[str, Source]) -> list[Record]: features, "libretro", tosimage.group(2), core=guard.group(1) ) records.append( - _record( + launcher_record( guard.group(1), "libretro", "core_option", @@ -210,7 +210,7 @@ def hatari_libretro(sources: dict[str, Source]) -> list[Record]: files = [c for c in choices if c != named.group(1) and not c.startswith(builtin.group(1))] head = src.lines(tos_img.start(), own.end()) records.append( - _record( + launcher_record( "hatarib", "libretro", "fixed_name", @@ -228,7 +228,7 @@ def hatari_libretro(sources: dict[str, Source]) -> list[Record]: ) ) records.append( - _record( + launcher_record( "hatarib", "libretro", "core_option", @@ -245,7 +245,7 @@ def hatari_libretro(sources: dict[str, Source]) -> list[Record]: ) ) records.append( - _record( + launcher_record( "hatarib", "libretro", "copies", @@ -255,7 +255,7 @@ def hatari_libretro(sources: dict[str, Source]) -> list[Record]: search_dir="/".join(["bios", *folders]), passes_to=f"bios/{own.group(2)}/", fails_when_missing=False, - depends_on_option=_joined(key, TARGET_ABSENT), + depends_on_option=joined(key, TARGET_ABSENT), ) ) return records @@ -318,7 +318,7 @@ def amiberry(sources: dict[str, Source]) -> list[Record]: for field, names, spans in lists: stage = src.find(rf"StageKickstart\(_model\.{field}\)", f"StageKickstart({field})") records.append( - _record( + launcher_record( "amiberry", "standalone", "names_searched", @@ -354,7 +354,7 @@ def amiberry(sources: dict[str, Source]) -> list[Record]: for directory, match, key in ((roms.group(2), roms, "rom_path"), (whdboot.group(1), whdboot, "whdboot_path")): records.append( - _record( + launcher_record( "amiberry", "standalone", "passes_path", @@ -377,7 +377,7 @@ def amiberry(sources: dict[str, Source]) -> list[Record]: for field, names, spans in lists: call = src.find(rf"StageKickstart\(_model\.{field}\)", f"StageKickstart({field})") records.append( - _record( + launcher_record( "amiberry", "standalone", "copies", @@ -402,7 +402,7 @@ def amiberry(sources: dict[str, Source]) -> list[Record]: ): raise LauncherPatternMissing(src.path, "StageRomKey copy when absent or resized") records.append( - _record( + launcher_record( "amiberry", "standalone", "copies", @@ -434,7 +434,7 @@ def winuae(sources: dict[str, Source]) -> list[Record]: ) message, throw_line = _throw_message(src, lookup.end(), body[1]) records.append( - _record( + launcher_record( "winuae", "standalone", "names_searched", @@ -465,7 +465,7 @@ def winuae(sources: dict[str, Source]) -> list[Record]: loop.start(), ) records.append( - _record( + launcher_record( "winuae", "standalone", "copies", @@ -507,7 +507,7 @@ def openmsx(sources: dict[str, Source]) -> list[Record]: ): start = block[0] + entry.start() records.append( - _record( + launcher_record( "openmsx", "standalone", "fixed_name", @@ -538,7 +538,7 @@ def openmsx(sources: dict[str, Source]) -> list[Record]: "OPENMSX_HOME environment", home.end(), ) records.append( - _record( + launcher_record( "openmsx", "standalone", "passes_path", diff --git a/scripts/scraper/retrobat_config_files.py b/scripts/scraper/retrobat_config_files.py index 3c8606fe5..abe160311 100644 --- a/scripts/scraper/retrobat_config_files.py +++ b/scripts/scraper/retrobat_config_files.py @@ -24,12 +24,12 @@ from .retrobat_generators import ( FEATURES, GENERATORS, TARGET_ABSENT, - _BIOS_ROOT, - _joined, - _record, + BIOS_ROOT, + joined, + launcher_record, feature_choices, ) -from .retrobat_render import _config_label, _covered, _path_parts, _render, _when +from .retrobat_render import config_label, covered_records, path_parts, render, when # Each extractor takes the sources by path and returns its records. @@ -68,7 +68,7 @@ def ares(sources: dict[str, Source]) -> list[Record]: ) sections = "/".join(m.group(1) for m in container) records.append( - _record( + launcher_record( "ares", "standalone", "names_searched", @@ -119,7 +119,7 @@ def mesen(sources: dict[str, Source]) -> list[Record]: except LauncherPatternMissing: fails = False records.append( - _record( + launcher_record( "mesen", "standalone", "copies", @@ -138,7 +138,7 @@ def mesen(sources: dict[str, Source]) -> list[Record]: def _name_of(src: Source, var: str, offset: int) -> tuple[str, str, list[tuple[int, int]]]: """A variable holding bios//, as (folder, name, lines).""" method = _method_of(src, offset) - rendered = _render(src, var, method[0], offset) + rendered = render(src, var, method[0], offset) if rendered is None or not rendered[0].startswith("bios/") or ", " in rendered[0]: raise LauncherPatternMissing( src.path, f"bios path held by {var} at line {src.line(offset)}" @@ -168,15 +168,15 @@ def desmume(sources: dict[str, Source]) -> list[Record]: folder, name, lines = _name_of(src, var, pair.start()) names.append(name) spans += lines - conditions, returns = _when(src, pair.start()) - config = _config_label(src, pair.start(), "ini") + conditions, returns = when(src, pair.start()) + config = config_label(src, pair.start(), "ini") records = [ - _record( + launcher_record( "desmume", "standalone", "fixed_name", names, - _path_parts(src, *returns, *spans, src.lines(pair.start(), block[1])), + path_parts(src, *returns, *spans, src.lines(pair.start(), block[1])), case_insensitive=True, search_dir=folder, passes_to=f"{config} [{flag.group(1)}] " @@ -187,7 +187,7 @@ def desmume(sources: dict[str, Source]) -> list[Record]: ) ] firmware = src.find( - rf'string (\w+) = Path\.Combine\({_BIOS_ROOT}, "([^"]+)"\);\s*' + rf'string (\w+) = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);\s*' r'if \(SystemConfig\.isOptSet\("(\w+)"\)[^\n]*\)\s*\{\s*' r'string (\w+) = SystemConfig\["\3"\];\s*if \(File\.Exists\(\4\)\)\s*\1 = \4;\s*\}\s*' r"if \(File\.Exists\(\1\)\)\s*\{", @@ -206,14 +206,14 @@ def desmume(sources: dict[str, Source]) -> list[Record]: fw_block[0], fw_block[1], ) - conditions, returns = _when(src, firmware.start()) + conditions, returns = when(src, firmware.start()) records.append( - _record( + launcher_record( "desmume", "standalone", "fixed_name", [firmware.group(2)], - _path_parts(src, *returns, src.lines(firmware.start(), fw_flag.end())), + path_parts(src, *returns, src.lines(firmware.start(), fw_flag.end())), case_insensitive=True, search_dir="bios", passes_to=f"{config} [{fw_write.group(1)}] {fw_write.group(2)}, only if the file exists", @@ -223,7 +223,7 @@ def desmume(sources: dict[str, Source]) -> list[Record]: ), ) ) - return _covered(src, records) + return covered_records(src, records) def melonds_dsi(sources: dict[str, Source]) -> list[Record]: @@ -256,7 +256,7 @@ def melonds_dsi(sources: dict[str, Source]) -> list[Record]: method[0], check.start(), ) - root = _render(src, decl.group(1), method[0], decl.start()) + root = render(src, decl.group(1), method[0], decl.start()) if root is None or not root[0].startswith("bios"): raise LauncherPatternMissing(src.path, f"bios folder of {var}") folders.add(root[0]) @@ -302,14 +302,14 @@ def melonds_dsi(sources: dict[str, Source]) -> list[Record]: choices, choice_lines = feature_choices(features, "melonds", region.group(1)) stem, _, extension = region.group(5).rpartition(".") nand_name = names[variables.index(region.group(6))] - config = _config_label(src, check.start(), "ini") + config = config_label(src, check.start(), "ini") records = [ - _record( + launcher_record( "melonds", "standalone", "fixed_name", names, - _path_parts( + path_parts( src, src.lines(boot.start(), boot.end()), src.lines(dsi.start(), forced.end()), @@ -323,7 +323,7 @@ def melonds_dsi(sources: dict[str, Source]) -> list[Record]: fails_when_missing=message, depends_on_option=mode, ), - _record( + launcher_record( "melonds", "standalone", "scans_dir", @@ -364,12 +364,12 @@ def jzintv(sources: dict[str, Source]) -> list[Record]: passed.append((add.start(), add.group(1), name, lines, add.end())) passed.sort() records = [ - _record( + launcher_record( "jzintv", "standalone", "fixed_name", [name for _, _, name, _, _ in passed], - _path_parts( + path_parts( src, *[span for p in passed for span in p[3]], (src.line(check.start()), throw_line), @@ -383,7 +383,7 @@ def jzintv(sources: dict[str, Source]) -> list[Record]: ) ] ecs = src.find( - rf'string (\w+) = Path\.Combine\({_BIOS_ROOT}, "([^"]+)"\);\s*if \(File\.Exists\(\1\)\)\s*\{{\s*' + rf'string (\w+) = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);\s*if \(File\.Exists\(\1\)\)\s*\{{\s*' r'commandArray\.Add\("(-\w+)"\);', "ECS ROM", ) @@ -400,12 +400,12 @@ def jzintv(sources: dict[str, Source]) -> list[Record]: "command file lookup", ) records.append( - _record( + launcher_record( "jzintv", "standalone", "fixed_name", [ecs.group(2)], - _path_parts( + path_parts( src, src.lines(commands.start(), commands.end()), src.lines(option.start(), warning.end()), @@ -420,7 +420,7 @@ def jzintv(sources: dict[str, Source]) -> list[Record]: ), ) ) - return _covered(src, records) + return covered_records(src, records) def blastem(sources: dict[str, Source]) -> list[Record]: @@ -445,18 +445,18 @@ def blastem(sources: dict[str, Source]) -> list[Record]: for call in src.find_all( r'SetBiosPath\((\w+), "(\w+)", (\w+), "([^"]+)"\);', "SetBiosPath call" ): - root = _render(src, call.group(3), _method_of(src, call.start())[0], call.start()) + root = render(src, call.group(3), _method_of(src, call.start())[0], call.start()) if root is None or root[0] != "bios": raise LauncherPatternMissing( src.path, f"bios folder passed at line {src.line(call.start())}" ) records.append( - _record( + launcher_record( "blastem", "standalone", "fixed_name", [call.group(4)], - _path_parts( + path_parts( src, *root[1], src.lines(call.start(), call.end()), @@ -468,10 +468,10 @@ def blastem(sources: dict[str, Source]) -> list[Record]: fails_when_missing=f"info log, {call.group(2)} left as it is", ) ) - return _covered(src, records) + return covered_records(src, records) -def _value_writes( +def value_writes( src: Source, emulator: str, build: str, start: int = 0, end: int | None = None ) -> list[Record]: """Configuration values that resolve under the bios folder. @@ -493,24 +493,24 @@ def _value_writes( writer, section, value = write.group(1), args[0].lstrip("@"), args[2] key = _unescape(key_literal.group(1)) method = _method_of(src, write.start()) - rendered = _render(src, value, method[0], write.start()) + rendered = render(src, value, method[0], write.start()) if rendered is None or not rendered[0].startswith("bios"): continue - conditions, returns = _when(src, write.start()) + conditions, returns = when(src, write.start()) section = _unescape(section[1:-1]) if section != "null" else "" - target = f"{_config_label(src, write.start(), writer)} " + ( + target = f"{config_label(src, write.start(), writer)} " + ( f"[{section}] {key}" if section else key ) span = src.lines( _statement_start(src, write.start()), write.end() + len(_call_args(src, write.end() - 1)), ) - ref = _path_parts(src, *returns, *rendered[1], span) + ref = path_parts(src, *returns, *rendered[1], span) depends = ", ".join(conditions) or None folder, _, name = rendered[0].rpartition("/") if "." not in name or ", " in rendered[0]: records.append( - _record( + launcher_record( emulator, build, "passes_path", @@ -528,7 +528,7 @@ def _value_writes( if guarded: depends = ", ".join(c for c in conditions if c != f"File.Exists({variable})") or None records.append( - _record( + launcher_record( emulator, build, "fixed_name", @@ -553,7 +553,7 @@ def _value_writes( def dolphin(sources: dict[str, Source]) -> list[Record]: src = sources[f"{GENERATORS}/Dolphin.Generator.cs"] - records = _value_writes(src, "dolphin", "standalone") + records = value_writes(src, "dolphin", "standalone") if not records: raise LauncherPatternMissing(src.path, "GBA BIOS write") method = src.find(r"private void CopySegaBoot\(string path\)", "CopySegaBoot") @@ -567,7 +567,7 @@ def dolphin(sources: dict[str, Source]) -> list[Record]: block = src.block_at(array.end() - 1) names = [] for item in _split_top(src.text[block[0] + 1 : block[1] - 1].strip(), ","): - rendered = _render(src, item, body[0], block[0]) + rendered = render(src, item, body[0], block[0]) if rendered is None or not rendered[0].startswith("bios/"): raise LauncherPatternMissing(src.path, f"segaboot candidate {item}") names.append(rendered[0][len("bios/") :]) @@ -585,15 +585,15 @@ def dolphin(sources: dict[str, Source]) -> list[Record]: body[1], ) call = src.find(r"CopySegaBoot\(path\);", "CopySegaBoot call") - conditions, returns = _when(src, call.start()) - destination = _render(src, target.group(1), body[0], target.start()) + conditions, returns = when(src, call.start()) + destination = render(src, target.group(1), body[0], target.start()) records.append( - _record( + launcher_record( "dolphin", "standalone", "copies", names, - _path_parts( + path_parts( src, *returns, src.lines(_statement_start(src, call.start()), call.end()), @@ -603,21 +603,21 @@ def dolphin(sources: dict[str, Source]) -> list[Record]: search_dir="bios", passes_to=destination[0] if destination else target.group(1), fails_when_missing=f"warning '{_unescape(warning.group(1))}' when the target is absent too", - depends_on_option=_joined( + depends_on_option=joined( *conditions, "first name found", "the target is absent, smaller or older", ), ) ) - return _covered(src, records, skip=(r"DolphinTool\.exe",)) + return covered_records(src, records, skip=(r"DolphinTool\.exe",)) def raine(sources: dict[str, Source]) -> list[Record]: src = sources[f"{GENERATORS}/Raine.Generator.cs"] - records = _value_writes(src, "raine", "standalone") + records = value_writes(src, "raine", "standalone") if not any(r["kind"] == "fixed_name" for r in records): raise LauncherPatternMissing(src.path, "neocd_bios write") - return _covered(src, records) + return covered_records(src, records) def gsplus(sources: dict[str, Source]) -> list[Record]: @@ -638,16 +638,16 @@ def gsplus(sources: dict[str, Source]) -> list[Record]: write = src.find( rf'(\w+)\.WriteValue\(null, "(\w+)", {first.group(1)}\);', "ROM path write" ) - conditions, returns = _when(src, write.start()) + conditions, returns = when(src, write.start()) # The test on the name found is the selection itself, not a condition. conditions = [c for c in conditions if first.group(1) not in c] - target = f"{_config_label(src, write.start(), write.group(1))} {write.group(2)}" - record = _record( + target = f"{config_label(src, write.start(), write.group(1))} {write.group(2)}" + record = launcher_record( "gsplus", "standalone", "names_searched", _strings(listed.group(2)), - _path_parts( + path_parts( src, *returns, src.lines(listed.start(), listed.end()), @@ -660,17 +660,17 @@ def gsplus(sources: dict[str, Source]) -> list[Record]: fails_when_missing=False, depends_on_option=", ".join(conditions) or None, ) - return _covered(src, [record]) + return covered_records(src, [record]) def rpcs3(sources: dict[str, Source]) -> list[Record]: src = sources[f"{GENERATORS}/Rpcs3.Generator.cs"] marker = src.find( - rf"string (\w+) = (Path\.Combine\(path, [^;]+\));\s*string \w+ = {_BIOS_ROOT};", + rf"string (\w+) = (Path\.Combine\(path, [^;]+\));\s*string \w+ = {BIOS_ROOT};", "installed firmware marker", ) pup = src.find( - rf'string (\w+) = {_BIOS_ROOT};\s*string (\w+) = Path\.Combine\(\1, "([^"]+)"\);', + rf'string (\w+) = {BIOS_ROOT};\s*string (\w+) = Path\.Combine\(\1, "([^"]+)"\);', "PS3 update file", marker.start(), ) @@ -687,13 +687,13 @@ def rpcs3(sources: dict[str, Source]) -> list[Record]: check.end(), ) returned = src.find(r"return new ProcessStartInfo\(\)", "install launch", install.end()) - installed = _render(src, marker.group(2), method[0], marker.start()) - record = _record( + installed = render(src, marker.group(2), method[0], marker.start()) + record = launcher_record( "rpcs3", "standalone", "fixed_name", [pup.group(3)], - _path_parts(src, src.lines(marker.start(), src.block_at(returned.end())[1])), + path_parts(src, src.lines(marker.start(), src.block_at(returned.end())[1])), case_insensitive=True, search_dir="bios", passes_to=( @@ -702,7 +702,7 @@ def rpcs3(sources: dict[str, Source]) -> list[Record]: fails_when_missing=message, depends_on_option=f"{installed[0] if installed else marker.group(2)} absent", ) - return _covered(src, [record]) + return covered_records(src, [record]) def bizhawk_gb(sources: dict[str, Source]) -> list[Record]: @@ -728,7 +728,7 @@ def bizhawk_gb(sources: dict[str, Source]) -> list[Record]: flag.start(), ) default = src.find( - rf'string {var} = Path\.Combine\({_BIOS_ROOT}, "([^"]+)"\);', + rf'string {var} = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);', "default GB BIOS", method[0], flag.start(), @@ -736,14 +736,14 @@ def bizhawk_gb(sources: dict[str, Source]) -> list[Record]: chosen = list( re.compile( rf'(?:else )?if \(system == "(\w+)"\)\s*' - rf'{var} = Path\.Combine\({_BIOS_ROOT}, "([^"]+)"\);' + rf'{var} = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);' ).finditer(code, default.end(), flag.start()) ) if code[default.end() : flag.start()].count(f"{var} =") != len(chosen): raise LauncherPatternMissing( src.path, f"{var} choice at line {src.line(default.start())}" ) - ref = _path_parts( + ref = path_parts( src, src.lines(core.start(), core.end()), src.lines(default.start(), flag.end()) ) others = " && ".join(f'system != "{m.group(1)}"' for m in chosen) @@ -751,7 +751,7 @@ def bizhawk_gb(sources: dict[str, Source]) -> list[Record]: slots += [(m.group(1), m.group(2), f'system == "{m.group(1)}"') for m in chosen] for slot, name, system in slots: records.append( - _record( + launcher_record( "bizhawk", "standalone", "fixed_name", @@ -770,7 +770,7 @@ def bizhawk_gb(sources: dict[str, Source]) -> list[Record]: ), ) ) - return _covered( + return covered_records( src, records, # A DSi NAND boot copies the game itself to bios/dsi_nand.bin. diff --git a/scripts/scraper/retrobat_config_folders.py b/scripts/scraper/retrobat_config_folders.py index 975c99ca9..f5c463695 100644 --- a/scripts/scraper/retrobat_config_folders.py +++ b/scripts/scraper/retrobat_config_folders.py @@ -16,9 +16,9 @@ from .csharp_source import ( _throw_message, source_ref, ) -from .retrobat_config_files import _value_writes -from .retrobat_generators import GENERATORS, TARGET_ABSENT, _BIOS_ROOT, _joined, _record -from .retrobat_render import _config_label, _covered, _path_parts, _render, _when +from .retrobat_config_files import value_writes +from .retrobat_generators import GENERATORS, TARGET_ABSENT, BIOS_ROOT, joined, launcher_record +from .retrobat_render import config_label, covered_records, path_parts, render, when from model.launcherrecords import join_emulators @@ -37,8 +37,8 @@ def _copies_if_absent( ).finditer(code, start, end): target_var, source_var = copy.groups() method = _method_of(src, copy.start()) - source = _render(src, source_var, method[0], copy.start()) - target = _render(src, target_var, method[0], copy.start()) + source = render(src, source_var, method[0], copy.start()) + target = render(src, target_var, method[0], copy.start()) if source is None or target is None or not source[0].startswith("bios/"): raise LauncherPatternMissing(src.path, f"copy at line {src.line(copy.start())}") folder, _, name = source[0].rpartition("/") @@ -50,19 +50,19 @@ def _copies_if_absent( folders = {folder for _, folder, _, _ in copies} if len(folders) != 1: raise LauncherPatternMissing(src.path, f"one source folder for {destination}") - conditions, returns = _when(src, copies[0][0]) + conditions, returns = when(src, copies[0][0]) records.append( - _record( + launcher_record( emulator, build, "copies", [name for _, _, name, _ in copies], - _path_parts(src, *returns, *[s for c in copies for s in c[3]]), + path_parts(src, *returns, *[s for c in copies for s in c[3]]), case_insensitive=True, search_dir=folders.pop(), passes_to=f"{destination}/", fails_when_missing=False, - depends_on_option=_joined(*conditions, TARGET_ABSENT), + depends_on_option=joined(*conditions, TARGET_ABSENT), ) ) if not records: @@ -78,7 +78,7 @@ def dosbox_copies(sources: dict[str, Source]) -> list[Record]: (f"{GENERATORS}/DosBoxPure.Generator.cs", "dosbox-pure"), (f"{GENERATORS}/DosBoxStaging.Generator.cs", "dosbox-staging"), ) - for record in _covered( + for record in covered_records( sources[path], _copies_if_absent(sources[path], emulator, "standalone") ) ] @@ -101,7 +101,7 @@ def capsimg(sources: dict[str, Source]) -> list[Record]: record["source_ref"] = source_ref( (src.path, [(src.line(cores.start()), core_lines[1]), src.statement_span(block)]) ) - record["depends_on_option"] = _joined( + record["depends_on_option"] = joined( f'core in {cores.group(1)}, rom extension "{gate.group(1)}"', TARGET_ABSENT ) return [record] @@ -112,20 +112,20 @@ def tsugaru(sources: dict[str, Source]) -> list[Record]: src = sources[f"{GENERATORS}/Tsugaru.Generator.cs"] code = _code(src) first = src.find( - rf'if \(Directory\.Exists\((Path\.Combine\({_BIOS_ROOT}, "[^"]+"\))\)\)\s*(\w+) = \1;', + rf'if \(Directory\.Exists\((Path\.Combine\({BIOS_ROOT}, "[^"]+"\))\)\)\s*(\w+) = \1;', "first FM Towns folder", ) var = first.group(2) method = _method_of(src, first.start()) unset = src.find(rf"string {var} = null;", f"{var} declaration", method[0], first.start()) - folders = [_render(src, first.group(1), method[0], first.start())] + folders = [render(src, first.group(1), method[0], first.start())] names, end = set(), first.end() step = re.compile( rf'\s*if \(!File\.Exists\(Path\.Combine\({var}, "([^"]+)"\)\)\)\s*{var} = ([^;]+);' ) while more := step.match(code, end): names.add(more.group(1)) - folders.append(_render(src, more.group(2), method[0], more.start())) + folders.append(render(src, more.group(2), method[0], more.start())) end = more.end() final = re.compile( rf'\s*if \(!File\.Exists\(Path\.Combine\({var}, "([^"]+)"\)\)\)\s*\{{' @@ -144,12 +144,12 @@ def tsugaru(sources: dict[str, Source]) -> list[Record]: ) if info is None or len(names) != 1: raise LauncherPatternMissing(src.path, "FMT_SYS.ROM missing branch") - record = _record( + record = launcher_record( "tsugaru", "standalone", "passes_path", sorted(names), - _path_parts( + path_parts( src, src.lines(unset.start(), unset.end()), src.lines(first.start(), cmos.end()) ), case_insensitive=True, @@ -164,7 +164,7 @@ def tsugaru(sources: dict[str, Source]) -> list[Record]: f" ({var} stays null otherwise when {final.group(1)} is checked)" ), ) - return _covered(src, [record]) + return covered_records(src, [record]) def _indexer_writes(src: Source, emulator: str, writer: str) -> list[Record]: @@ -173,20 +173,20 @@ def _indexer_writes(src: Source, emulator: str, writer: str) -> list[Record]: records = [] for write in re.compile(rf'\b{writer}\["([^"]+)"\] = ([^;]+);').finditer(code): method = _method_of(src, write.start()) - rendered = _render(src, src.text[write.start(2) : write.end(2)], method[0], write.start()) + rendered = render(src, src.text[write.start(2) : write.end(2)], method[0], write.start()) if rendered is None or not rendered[0].startswith("bios"): continue - conditions, returns = _when(src, write.start()) + conditions, returns = when(src, write.start()) records.append( - _record( + launcher_record( emulator, "standalone", "passes_path", [], - _path_parts(src, *returns, *rendered[1], src.lines(write.start(), write.end())), + path_parts(src, *returns, *rendered[1], src.lines(write.start(), write.end())), search_dir=rendered[0], passes_to=( - f"{_config_label(src, write.start(), writer)} {write.group(1)} = {rendered[0]}" + f"{config_label(src, write.start(), writer)} {write.group(1)} = {rendered[0]}" ), fails_when_missing=False, depends_on_option=", ".join(conditions) or None, @@ -199,17 +199,17 @@ def _indexer_writes(src: Source, emulator: str, writer: str) -> list[Record]: def eka2l1(sources: dict[str, Source]) -> list[Record]: src = sources[f"{GENERATORS}/Eka2l1.Generator.cs"] - return _covered(src, _indexer_writes(src, "eka2l1", "yml")) + return covered_records(src, _indexer_writes(src, "eka2l1", "yml")) def fbneo(sources: dict[str, Source]) -> list[Record]: src = sources[f"{GENERATORS}/Fbneo.Generator.cs"] - return _covered(src, _indexer_writes(src, "fbneo", "cfg")) + return covered_records(src, _indexer_writes(src, "fbneo", "cfg")) def snes9x(sources: dict[str, Source]) -> list[Record]: src = sources[f"{GENERATORS}/Snes9x.Generator.cs"] - entry = src.find(rf'\{{ "([^"]+)", (Path\.Combine\({_BIOS_ROOT}\)) \}}', "bios folder entry") + entry = src.find(rf'\{{ "([^"]+)", (Path\.Combine\({BIOS_ROOT}\)) \}}', "bios folder entry") loop = src.find( r"foreach \(KeyValuePair pair in (\w+)\)", "path loop", entry.end() ) @@ -220,18 +220,18 @@ def snes9x(sources: dict[str, Source]) -> list[Record]: body[0], body[1], ) - config = _config_label(src, write.start(), write.group(1)) - record = _record( + config = config_label(src, write.start(), write.group(1)) + record = launcher_record( "snes9x", "standalone", "passes_path", [], - _path_parts(src, src.lines(entry.start(), entry.end()), src.lines(loop.start(), body[1])), + path_parts(src, src.lines(entry.start(), entry.end()), src.lines(loop.start(), body[1])), search_dir="bios", passes_to=f"{config} [{write.group(2)}] {entry.group(1)} = bios", fails_when_missing=False, ) - return _covered(src, [record]) + return covered_records(src, [record]) def value_folders(sources: dict[str, Source]) -> list[Record]: @@ -242,10 +242,10 @@ def value_folders(sources: dict[str, Source]) -> list[Record]: (f"{GENERATORS}/Flycast.Generator.cs", "flycast", (r"string libretroPath = ",)), (f"{GENERATORS}/ScummVm.Generator.cs", "scummvm", ()), ): - found = _value_writes(sources[path], emulator, "standalone") + found = value_writes(sources[path], emulator, "standalone") if not found: raise LauncherPatternMissing(path, "bios folder write") - records += _covered(sources[path], found, skip=skip) + records += covered_records(sources[path], found, skip=skip) return records @@ -260,21 +260,21 @@ def demul(sources: dict[str, Source]) -> list[Record]: block[1], ) method = _method_of(src, listing.start()) - config = _config_label(src, loop.start(), loop.group(1)) + config = config_label(src, loop.start(), loop.group(1)) records = [] for index, item in enumerate(_split_top(src.text[block[0] + 1 : block[1] - 1].strip(), ",")): - rendered = _render(src, item, method[0], listing.start()) + rendered = render(src, item, method[0], listing.start()) if rendered is None: raise LauncherPatternMissing(src.path, f"rom path {item}") if not rendered[0].startswith("bios"): continue records.append( - _record( + launcher_record( "demul", "standalone", "passes_path", [], - _path_parts( + path_parts( src, *rendered[1], src.lines(listing.start(), block[1]), @@ -285,7 +285,7 @@ def demul(sources: dict[str, Source]) -> list[Record]: fails_when_missing=False, ) ) - return _covered(src, records) + return covered_records(src, records) def bsyndrome(sources: dict[str, Source]) -> list[Record]: @@ -296,17 +296,17 @@ def bsyndrome(sources: dict[str, Source]) -> list[Record]: "path argument", ): method = _method_of(src, arg.start()) - rendered = _render(src, arg.group(3), method[0], arg.start()) + rendered = render(src, arg.group(3), method[0], arg.start()) if rendered is None or not rendered[0].startswith("bios"): continue - conditions, returns = _when(src, arg.start()) + conditions, returns = when(src, arg.start()) records.append( - _record( + launcher_record( "bsyndrome", "standalone", "passes_path", [], - _path_parts(src, *returns, *rendered[1], src.lines(arg.start(), arg.end())), + path_parts(src, *returns, *rendered[1], src.lines(arg.start(), arg.end())), search_dir=rendered[0], passes_to=f"command line {arg.group(2)}={rendered[0]}", fails_when_missing=False, @@ -315,7 +315,7 @@ def bsyndrome(sources: dict[str, Source]) -> list[Record]: ) if not records: raise LauncherPatternMissing(src.path, "bios folder argument") - return _covered(src, records) + return covered_records(src, records) def xm6pro(sources: dict[str, Source]) -> list[Record]: @@ -335,23 +335,23 @@ def xm6pro(sources: dict[str, Source]) -> list[Record]: loop.end(), body[1], ) - folder = _render(src, copy.group(2), body[0], copy.start()) + folder = render(src, copy.group(2), body[0], copy.start()) if folder is None or not folder[0].startswith("bios/"): raise LauncherPatternMissing(src.path, "keropi folder") - conditions, _ = _when(src, loop.start()) - record = _record( + conditions, _ = when(src, loop.start()) + record = launcher_record( "xm6pro", "standalone", "copies", names, - _path_parts(src, (src.line(table.start()), lines[1]), src.lines(method.start(), body[1])), + path_parts(src, (src.line(table.start()), lines[1]), src.lines(method.start(), body[1])), case_insensitive=True, search_dir=folder[0], passes_to="/", fails_when_missing=False, - depends_on_option=_joined(*conditions, TARGET_ABSENT), + depends_on_option=joined(*conditions, TARGET_ABSENT), ) - return _covered(src, [record]) + return covered_records(src, [record]) def arcadeduck(sources: dict[str, Source]) -> list[Record]: @@ -389,9 +389,9 @@ def arcadeduck(sources: dict[str, Source]) -> list[Record]: ) src.find(r"candidates\.Add\(biosRoot\);", "bios folder last", body[0], body[1]) message, _ = _throw_message(src, body[0], body[1]) - root = src.find(rf"string biosPath = {_BIOS_ROOT};", "bios root") + root = src.find(rf"string biosPath = {BIOS_ROOT};", "bios root") write = src.find(r'ini\.WriteValue\("(\w+)", "(\w+)", biosPath\);', "SearchDirectory write") - config = _config_label(src, write.start(), "ini") + config = config_label(src, write.start(), "ini") target = f"{config} [{write.group(1)}] {write.group(2)}" database_file = "/".join(_strings(database.group(1))) ref = source_ref( @@ -409,7 +409,7 @@ def arcadeduck(sources: dict[str, Source]) -> list[Record]: ), ) records = [ - _record( + launcher_record( "arcadeduck", "standalone", "names_searched", @@ -420,7 +420,7 @@ def arcadeduck(sources: dict[str, Source]) -> list[Record]: passes_to=f"{target} = ", fails_when_missing=message, ), - _record( + launcher_record( "arcadeduck", "standalone", "names_searched", @@ -433,7 +433,7 @@ def arcadeduck(sources: dict[str, Source]) -> list[Record]: fails_when_missing=message, depends_on_option=f"{database_file} names no archive for {fixed.group(1)}", ), - _record( + launcher_record( "arcadeduck", "standalone", "passes_path", @@ -445,4 +445,4 @@ def arcadeduck(sources: dict[str, Source]) -> list[Record]: depends_on_option="no bios archive known for the game's system", ), ] - return _covered(src, records) + return covered_records(src, records) diff --git a/scripts/scraper/retrobat_generators.py b/scripts/scraper/retrobat_generators.py index 293b6b197..0c8ae8ec3 100644 --- a/scripts/scraper/retrobat_generators.py +++ b/scripts/scraper/retrobat_generators.py @@ -86,12 +86,12 @@ def feature_choices( TARGET_ABSENT = "the target does not exist" -def _joined(*parts: str | None) -> str | None: +def joined(*parts: str | None) -> str | None: """Conditions of a record, joined, None when there are none.""" return ", ".join(part for part in parts if part) or None -def _record( +def launcher_record( emulator: str, build: str, kind: str, names: list[str], ref: str, **fields: object ) -> Record: record: Record = {"emulator": emulator, "build": build, "kind": kind, "names": names} @@ -112,15 +112,15 @@ GUARDED_WRITES = { f"{GENERATORS}/mGBA.Generator.cs": "mgba", } -_TRANSPARENT = re.compile(r"(?:using\s*\(.*\)|try)") -_IF = re.compile(r"(?:else\s+)?if\s*\((.*)\)") +TRANSPARENT = re.compile(r"(?:using\s*\(.*\)|try)") +IF = re.compile(r"(?:else\s+)?if\s*\((.*)\)") _GUARD = re.compile( r'if \(File\.Exists\((\w+)\)\)\s*(\w+)\.WriteValue\("([^"]*)", "([^"]+)", ([^;\n]+)\);' ) -_BIOS_ROOT = r'(?:Program\.)?AppConfig\.GetFullPath\("bios"\)' +BIOS_ROOT = r'(?:Program\.)?AppConfig\.GetFullPath\("bios"\)' -def _negate(condition: str) -> str: +def negate(condition: str) -> str: """The condition under which an early return is not taken. A conjunction of inequalities becomes the disjunction of equalities, @@ -157,17 +157,17 @@ def _conditions(src: Source, offset: int) -> Reach | None: cond = _call_args(src, paren) tail = re.compile(r"\s*return\b[^;]*;").match(src.text, paren + len(cond) + 2) if tail: - returns.append(_negate(" ".join(cond.split()))) + returns.append(negate(" ".join(cond.split()))) spans.append(src.lines(block[0] + found.start(), tail.end())) return block, returns + enclosing[::-1], spans - condition = _IF.fullmatch(header) + condition = IF.fullmatch(header) if condition: text = " ".join(condition.group(1).split()) switch = re.fullmatch( r'SystemConfig\.isOptSet\("(\w+)"\) && SystemConfig\.getOptBoolean\("\1"\)', text ) enclosing.append(f"{switch.group(1)} on" if switch else text) - elif not _TRANSPARENT.fullmatch(header): + elif not TRANSPARENT.fullmatch(header): return None return None @@ -194,10 +194,10 @@ def _config_name(src: Source, method: tuple[int, int], writer: str) -> str: return files.pop() -def _root_writes(src: Source, emulator: str) -> list[Record]: +def root_writes(src: Source, emulator: str) -> list[Record]: """Configuration keys that receive the bios folder itself.""" records = [] - for root in re.finditer(rf"string (\w+) = {_BIOS_ROOT};", src.text): + for root in re.finditer(rf"string (\w+) = {BIOS_ROOT};", src.text): root_reach = _conditions(src, root.start()) if root_reach is None: continue @@ -225,7 +225,7 @@ def _root_writes(src: Source, emulator: str) -> list[Record]: folder, declared = folders[held] target = f"[{section}] {key}" if section else key records.append( - _record( + launcher_record( emulator, "standalone", "passes_path", @@ -271,20 +271,20 @@ def _guarded_write(src: Source, emulator: str, guard: re.Match[str]) -> Record | method, conditions, returns = reached decls = list( re.compile( - rf"string {var} = Path\.Combine\((\w+|{_BIOS_ROOT}), ((?:{STRING}, )*{STRING})\);" + rf"string {var} = Path\.Combine\((\w+|{BIOS_ROOT}), ((?:{STRING}, )*{STRING})\);" ).finditer(src.text, method[0], guard.start()) ) if not decls or re.search(rf"\b{var}\s*=[^=]", src.text[decls[-1].end() : guard.start()]): return None decl = decls[-1] root = decl.group(1) - if not re.fullmatch(_BIOS_ROOT, root) and not re.search( - rf"string {root} = {_BIOS_ROOT};", src.text[method[0] : decl.start()] + if not re.fullmatch(BIOS_ROOT, root) and not re.search( + rf"string {root} = {BIOS_ROOT};", src.text[method[0] : decl.start()] ): return None *folders, name = _strings(decl.group(2)) target = f"[{section}] {key}" if section else key - return _record( + return launcher_record( emulator, "standalone", "fixed_name", @@ -313,7 +313,7 @@ def guarded_writes_in(src: Source, emulator: str) -> list[Record]: records = [record for record in found if record is not None] if not records: raise LauncherPatternMissing(src.path, "File.Exists guarded WriteValue") - return records + _root_writes(src, emulator) + return records + root_writes(src, emulator) def guarded_writes(sources: dict[str, Source]) -> list[Record]: diff --git a/scripts/scraper/retrobat_playstation.py b/scripts/scraper/retrobat_playstation.py index 0d43113c5..4f6e4eb19 100644 --- a/scripts/scraper/retrobat_playstation.py +++ b/scripts/scraper/retrobat_playstation.py @@ -15,7 +15,7 @@ from .csharp_source import ( _unique, source_ref, ) -from .retrobat_generators import BIOS, FEATURES, GENERATORS, _record, feature_choices +from .retrobat_generators import BIOS, FEATURES, GENERATORS, launcher_record, feature_choices def pcsx2(sources: dict[str, Source]) -> list[Record]: @@ -49,7 +49,7 @@ def pcsx2(sources: dict[str, Source]) -> list[Record]: decl = src.find(rf"var {var} = new string\[\] \{{", f"Qt {var}", qt_body[0], qt_body[1]) names, lines = _array_at(src, decl.end() - 1) records.append( - _record( + launcher_record( "pcsx2", "standalone", "names_searched", @@ -89,7 +89,7 @@ def pcsx2(sources: dict[str, Source]) -> list[Record]: ) sub = "/".join(_strings(folder.group(1))) records.append( - _record( + launcher_record( "pcsx2", "standalone", "names_searched", @@ -129,7 +129,7 @@ def pcsx2_libretro(sources: dict[str, Source]) -> list[Record]: choices, choice_lines = feature_choices(features, "libretro", option.group(1), core="pcsx2") sub = "/".join(_strings(folder.group(1))) records = [ - _record( + launcher_record( "pcsx2", "libretro", "core_option", @@ -173,7 +173,7 @@ def pcsx2_libretro(sources: dict[str, Source]) -> list[Record]: ) auto_message, _ = _throw_message(src, auto.end(), auto_write.start()) records.append( - _record( + launcher_record( "pcsx2", "libretro", "scans_dir", @@ -259,7 +259,7 @@ def psx_cascades(sources: dict[str, Source]) -> list[Record]: keys = _unique(re.findall(r'\w+\["([^"]+)"\]\s*=', src.text[branch[0] : branch[1]])) ref = source_ref((path, [src.lines(cascade.start(), original_end)])) records.append( - _record( + launcher_record( emulator, build, "names_searched", @@ -277,7 +277,7 @@ def psx_cascades(sources: dict[str, Source]) -> list[Record]: if fallback: checked = "File.Exists" in fallback_text records.append( - _record( + launcher_record( emulator, build, "fixed_name", @@ -311,7 +311,7 @@ def duckstation(sources: dict[str, Source]) -> list[Record]: cleared = src.block_at(block[1]) choices, choice_lines = feature_choices(features, "duckstation", option.group(1)) return [ - _record( + launcher_record( "duckstation", "standalone", "passes_path", @@ -322,7 +322,7 @@ def duckstation(sources: dict[str, Source]) -> list[Record]: fails_when_missing=False, depends_on_option=f"{option.group(1)} unset", ), - _record( + launcher_record( "duckstation", "standalone", "core_option", diff --git a/scripts/scraper/retrobat_render.py b/scripts/scraper/retrobat_render.py index 83f2d92c0..1bfe583a6 100644 --- a/scripts/scraper/retrobat_render.py +++ b/scripts/scraper/retrobat_render.py @@ -24,12 +24,12 @@ from .csharp_source import ( from .retrobat_generators import ( FEATURES, GENERATORS, - _BIOS_ROOT, - _IF, - _TRANSPARENT, - _negate, - _record, - _root_writes, + BIOS_ROOT, + IF, + TRANSPARENT, + negate, + launcher_record, + root_writes, feature_choices, ) @@ -56,7 +56,7 @@ def _negated(condition: str) -> str: """not condition, written as a C# reader would.""" if re.fullmatch(_ATOM, condition): return condition[1:] if condition.startswith("!") else f"!{condition}" - return _negate(condition) + return negate(condition) def _owner_condition(src: Source, start: int) -> str | None: @@ -65,7 +65,7 @@ def _owner_condition(src: Source, start: int) -> str | None: before = code[:start].rstrip() if before.endswith("}"): block = max(b for b in src.blocks() if b[1] == len(before)) - owner = _IF.fullmatch(src.header(block)) + owner = IF.fullmatch(src.header(block)) return owner.group(1) if owner else None if not before.endswith(";"): return None @@ -94,7 +94,7 @@ def _braceless_if(src: Source, offset: int) -> str | None: return " ".join(condition.split()) -def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: +def render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: """A path expression as text, with the lines of the declarations it read.""" expr = " ".join(expr.split()) fixed = _render_fixed(expr) @@ -102,11 +102,11 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: return fixed replaced = re.fullmatch(rf"(.+)\.Replace\({STRING}, {STRING}\)", expr) if replaced: - return _render(src, replaced.group(1), scope, before) + return render(src, replaced.group(1), scope, before) for wrapper in _WRAPPERS: inner = _wrapped(expr, wrapper) if inner is not None: - return _render(src, inner, scope, before) + return render(src, inner, scope, before) ternary = _split_top(expr, "?") if len(ternary) == 2: branches = _split_top(ternary[1], ":") @@ -118,7 +118,7 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: combine = _wrapped(expr, "Path.Combine") if combine is not None: base, *rest = _split_top(combine, ",") - root = _render(src, base, scope, before) + root = render(src, base, scope, before) literals = [re.fullmatch(STRING, part) for part in rest] if root is None or not all(literals): return None @@ -132,7 +132,7 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: def _render_fixed(expr: str) -> Rendered | None: """The expressions that name one known folder or file.""" - if re.fullmatch(_BIOS_ROOT, expr): + if re.fullmatch(BIOS_ROOT, expr): return "bios", [] changed = re.fullmatch(r'Path\.ChangeExtension\(exe, "(\.\w+)"\)', expr) if changed: @@ -149,8 +149,8 @@ def _render_choice( src: Source, condition: str, branches: list[str], scope: int, before: int ) -> Rendered | None: """A `condition ? a : b` expression.""" - first = _render(src, branches[0], scope, before) - second = _render(src, branches[1], scope, before) + first = render(src, branches[0], scope, before) + second = render(src, branches[1], scope, before) if first is None or second is None: return None return f"{first[0]} when {condition}, else {second[0]}", first[1] + second[1] @@ -167,7 +167,7 @@ def _render_terms(src: Source, terms: list[str], scope: int, before: int) -> Ren if term == '";"': pieces.append(";") continue - done = _render(src, term, scope, before) + done = render(src, term, scope, before) if done is None: return None pieces.append(done[0]) @@ -183,13 +183,13 @@ def _render_variable(src: Source, expr: str, scope: int, before: int) -> Rendere return (_PATH_PARAMS[expr], []) if expr in _PATH_PARAMS else None decl = decls[-1] decl_end = _statement_end(src, decl.end()) - declared = _render(src, src.text[decl.end() : decl_end], scope, decl.start()) + declared = render(src, src.text[decl.end() : decl_end], scope, decl.start()) if declared is None: return None text, spans = declared[0], [*declared[1], src.lines(decl.start(), decl_end)] for again in re.compile(rf"(? tuple[list[str], list[tuple[int, int]]]: +def when(src: Source, offset: int) -> tuple[list[str], list[tuple[int, int]]]: """Conditions under which the statement at offset runs, outermost first, with the lines of the early returns among them. @@ -249,14 +249,14 @@ def _when(src: Source, offset: int) -> tuple[list[str], list[tuple[int, int]]]: returns.append(_readable(_negated(cond))) spans.append(src.lines(block[0] + early.start(), tail.end())) return returns + found[::-1], spans - condition = _IF.fullmatch(header) + condition = IF.fullmatch(header) if condition: found.append(_readable(condition.group(1))) elif header == "else": previous = max(b for b in src.blocks() if b[1] <= block[0]) - owner = _IF.fullmatch(src.header(previous)) + owner = IF.fullmatch(src.header(previous)) found.append(f"not ({_readable(owner.group(1))})" if owner else "else") - elif not _TRANSPARENT.fullmatch(header) and not header.startswith(("catch", "lock")): + elif not TRANSPARENT.fullmatch(header) and not header.startswith(("catch", "lock")): found.append(header) raise LauncherPatternMissing(src.path, f"method around line {src.line(offset)}") @@ -280,10 +280,10 @@ def _argument_of(src: Source, method: tuple[int, int], parameter: str) -> Render return None arguments = _split_top(_call_args(src, calls[0].end() - 1), ",") caller = _method_of(src, calls[0].start()) - return _render(src, arguments[names.index(parameter)], caller[0], calls[0].start()) + return render(src, arguments[names.index(parameter)], caller[0], calls[0].start()) -def _config_label(src: Source, offset: int, writer: str) -> str: +def config_label(src: Source, offset: int, writer: str) -> str: """The file the writer variable opens, as a path under the emulator folder.""" method = _method_of(src, offset) code = _code(src) @@ -293,7 +293,7 @@ def _config_label(src: Source, offset: int, writer: str) -> str: ): paren = scope[0] + opened.end() - 1 target = _split_top(_call_args(src, paren), ",")[0] - rendered = _render(src, target, _method_of(src, paren)[0], paren) + rendered = render(src, target, _method_of(src, paren)[0], paren) if rendered is None: rendered = _argument_of(src, _method_of(src, paren), target) if rendered is not None: @@ -311,7 +311,7 @@ def _bios_lines(src: Source) -> list[int]: ) -def _covered(src: Source, records: list[Record], skip: tuple[str, ...] = ()) -> list[Record]: +def covered_records(src: Source, records: list[Record], skip: tuple[str, ...] = ()) -> list[Record]: """records, once every line of src that names the bios folder is in one. A line no record cites and no skip pattern describes is a construct the @@ -333,7 +333,7 @@ def _covered(src: Source, records: list[Record], skip: tuple[str, ...] = ()) -> return records -def _path_parts(src: Source, *spans: tuple[int, int]) -> str: +def path_parts(src: Source, *spans: tuple[int, int]) -> str: return source_ref((src.path, list(spans))) @@ -341,7 +341,7 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record """A default name under bios that an option replaces before it is written.""" code = _code(src) override = src.find( - rf"(?:string )?(\w+) = Path\.Combine\({_BIOS_ROOT}, SystemConfig\[\"(\w+)\"\]\);", + rf"(?:string )?(\w+) = Path\.Combine\({BIOS_ROOT}, SystemConfig\[\"(\w+)\"\]\);", "path taken from an option", ) var, option = override.groups() @@ -364,7 +364,7 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record skipped = re.findall( rf'SystemConfig\["{option}"\] != "(\w+)"', code[gate.start() : write.end()] ) - config = _config_label(src, write.start(), writer) + config = config_label(src, write.start(), writer) target = f"{config} [{section}] {key}" if section else f"{config} {key}" suffix = ", only if the file exists" if guarded else ", written without an existence check" fails = f"{key} not written" if guarded else "path written without an existence check" @@ -377,18 +377,18 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record fails = f"{', then '.join(fallback[0])}, instead, else {fails}" records = [] default = list( - re.compile(rf'string {var} = Path\.Combine\({_BIOS_ROOT}, "([^"]+)"\);').finditer( + re.compile(rf'string {var} = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);').finditer( code, method[0], gate.start() ) ) if default: records.append( - _record( + launcher_record( emulator, "standalone", "fixed_name", [default[-1].group(1)], - _path_parts(src, src.lines(default[-1].start(), default[-1].end()), write_span), + path_parts(src, src.lines(default[-1].start(), default[-1].end()), write_span), case_insensitive=True, search_dir="bios", passes_to=target + suffix, @@ -397,7 +397,7 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record ) ) records.append( - _record( + launcher_record( emulator, "standalone", "core_option", @@ -420,12 +420,12 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record f", {option} not {' or '.join(skipped)}" if skipped else "" ) records.append( - _record( + launcher_record( emulator, "standalone", "names_searched", names, - _path_parts(src, span, write_span), + path_parts(src, span, write_span), case_insensitive=True, search_dir="bios", passes_to=f"{target} = {suffix}", @@ -433,7 +433,7 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record depends_on_option=" or ".join(c for c in (unset, chosen) if c), ) ) - return records + _root_writes(src, emulator) + return records + root_writes(src, emulator) def _gate_span(src: Source, gate: re.Match[str], override: re.Match[str]) -> tuple[int, int]: @@ -471,7 +471,7 @@ def _fallback_names( found = re.compile( rf"if \(([^\n]*!File\.Exists\({var}\)[^\n]*)\)\s*" rf"{var} = new\[\] \{{ (?P(?:{STRING}(?:, )?)+) \}}\.Select\((?P\w+) => " - rf"Path\.Combine\({_BIOS_ROOT}, (?P=arg)\)\)\.FirstOrDefault\(File\.Exists\) \?\? {var};" + rf"Path\.Combine\({BIOS_ROOT}, (?P=arg)\)\)\.FirstOrDefault\(File\.Exists\) \?\? {var};" ).search(_code(src), start, end) if found is None: return None @@ -491,7 +491,7 @@ def option_paths(sources: dict[str, Source]) -> list[Record]: return [ record for path, emulator in OPTION_PATHS.items() - for record in _covered( + for record in covered_records( sources[path], _option_path_in(sources[path], sources[FEATURES], emulator) ) ] diff --git a/scripts/scraper/retrobat_xbox.py b/scripts/scraper/retrobat_xbox.py index dae2d53cc..a46f5fe75 100644 --- a/scripts/scraper/retrobat_xbox.py +++ b/scripts/scraper/retrobat_xbox.py @@ -5,7 +5,7 @@ from __future__ import annotations import re from .csharp_source import Record, Source, _array_at, _strings, _unique, source_ref -from .retrobat_generators import BIOS, FEATURES, GENERATORS, _joined, _record, feature_choices +from .retrobat_generators import BIOS, FEATURES, GENERATORS, joined, launcher_record, feature_choices from model.launcherrecords import join_emulators @@ -23,7 +23,7 @@ def xemu(sources: dict[str, Source]) -> list[Record]: "bootrom_path write", ) records.append( - _record( + launcher_record( "xemu", "standalone", "fixed_name", @@ -57,7 +57,7 @@ def xemu(sources: dict[str, Source]) -> list[Record]: ) choices, choice_lines = feature_choices(features, "xemu", flash.group(1)) records.append( - _record( + launcher_record( "xemu", "standalone", "core_option", @@ -103,7 +103,7 @@ def xemu(sources: dict[str, Source]) -> list[Record]: body[1], ) records.append( - _record( + launcher_record( "xemu", "standalone", "names_searched", @@ -122,7 +122,7 @@ def xemu(sources: dict[str, Source]) -> list[Record]: names, _ = _array_at(src, companions.end() - 1) loop = src.block_at(src.block_at(companions.end() - 1)[1]) records.append( - _record( + launcher_record( "xemu", "standalone", "fixed_name", @@ -143,7 +143,7 @@ def xemu(sources: dict[str, Source]) -> list[Record]: body[1], ) records.append( - _record( + launcher_record( "xemu", "standalone", "names_searched", @@ -192,7 +192,7 @@ def xemu_saves(sources: dict[str, Source]) -> list[Record]: ) hdd_key = src.find(r'ini\.WriteValue\("([\w.]+)", "(hdd_path)", "\'" \+ hddPath', "hdd_path write") records = [ - _record( + launcher_record( "xemu", "standalone", "fixed_name", @@ -216,7 +216,7 @@ def xemu_saves(sources: dict[str, Source]) -> list[Record]: " when absent, the disk image unzipped" ), fails_when_missing="never missing: the launcher writes both", - depends_on_option=_joined("the saves folder is set and exists", f"not ({chihiro_when})"), + depends_on_option=joined("the saves folder is set and exists", f"not ({chihiro_when})"), ) ] @@ -238,7 +238,7 @@ def xemu_saves(sources: dict[str, Source]) -> list[Record]: save = src.find(r"private void SaveChihiroEeprom\(\)", "SaveChihiroEeprom") save_body = src.block_at(save.end()) records.append( - _record( + launcher_record( "xemu, xemu-chihiro", "standalone", "copies", @@ -272,7 +272,7 @@ def xemu_saves(sources: dict[str, Source]) -> list[Record]: "Chihiro snapshot store", ) records.append( - _record( + launcher_record( "xemu, xemu-chihiro", "standalone", "fixed_name", @@ -321,7 +321,7 @@ def cxbx(sources: dict[str, Source]) -> list[Record]: " which the launcher writes beside the binary" ) records = [ - _record( + launcher_record( match.group(1), "standalone", "passes_path", @@ -336,7 +336,7 @@ def cxbx(sources: dict[str, Source]) -> list[Record]: first, *rest = fallbacks others = "neither core nor emulator is " + " or ".join(f'"{m.group(1)}"' for m in named) records.append( - _record( + launcher_record( first.group(1), "standalone", "passes_path", @@ -351,7 +351,7 @@ def cxbx(sources: dict[str, Source]) -> list[Record]: search_dir=f'', passes_to=passes_to, fails_when_missing=False, - depends_on_option=_joined( + depends_on_option=joined( others, *(f' when "{first.group(1)}" is not set' for m in rest), @@ -366,7 +366,7 @@ def cxbx(sources: dict[str, Source]) -> list[Record]: "EEPROM written from resources", ) records.append( - _record( + launcher_record( eeprom.group(3), "standalone", "fixed_name", @@ -411,7 +411,7 @@ def _cxbx_mount(src: Source, emulators: list[str]) -> list[Record]: when = f'rom extension "{iso.group(1)}"' emulator = join_emulators(emulators) return [ - _record( + launcher_record( emulator, "standalone", "fixed_name", @@ -423,7 +423,7 @@ def _cxbx_mount(src: Source, emulators: list[str]) -> list[Record]: fails_when_missing=vfs.group(3), depends_on_option=when, ), - _record( + launcher_record( emulator, "standalone", "fixed_name", diff --git a/scripts/scraper/retrodeck_launchers.py b/scripts/scraper/retrodeck_launchers.py index 0b2cf4dbf..127d7100c 100644 --- a/scripts/scraper/retrodeck_launchers.py +++ b/scripts/scraper/retrodeck_launchers.py @@ -22,8 +22,8 @@ from collections.abc import Callable from pathlib import PurePosixPath from typing import Any -from .retropie_scripts import Launcher, LauncherPatternMissing, _split, merge_records, source_ref -from .retropie_reader import _split_path +from .retropie_scripts import Launcher, LauncherPatternMissing, split, merge_records, source_ref +from .retropie_reader import split_path BIOS = "$bios_path" PLACEHOLDER = "RETRODECKBIOSDIR" @@ -93,7 +93,7 @@ class Script: continue shown = [c for c in branches if "$action" not in c] for part in re.split(r"\s+&&\s+|\s+\|\|\s+", stripped): - words = _split(part) + words = split(part) if words: found.append((number, words, part, shown)) return found @@ -165,7 +165,7 @@ class Component: continue if command == "cp" and len(words) >= 3 and _mentions_bios(words[-1]): source, target = words[-2], words[-1] - folder, name = _split_path(source) + folder, name = split_path(source) copies.setdefault((folder, depends), []).append((number, name, target)) continue if command == "tar" and "-C" in words and _mentions_bios(words[words.index("-C") + 1]): @@ -231,12 +231,12 @@ class Component: depends = key[-1] or None lines = [(path, n) for n, _v, _w in hits] if kind == "fixed_name": - folders = {_split_path(value)[0] for _n, value, _w in hits} + folders = {split_path(value)[0] for _n, value, _w in hits} if len(folders) != 1: raise LauncherPatternMissing( f"{path}:{hits[0][0]}", "fixed names in several folders" ) - names = list(dict.fromkeys(_split_path(value)[1] for _n, value, _w in hits)) + names = list(dict.fromkeys(split_path(value)[1] for _n, value, _w in hits)) wheres = list(dict.fromkeys(w for _n, _v, w in hits)) self.record( "fixed_name", names, lines, @@ -277,7 +277,7 @@ class Component: raise LauncherPatternMissing( f"{path}:{number}", f"link without a bios/ source: {words}" ) - folder, name = _split_path(paths[0]) + folder, name = split_path(paths[0]) self.record( "links", [name], [(path, number)], case_insensitive=False, search_dir=folder, passes_to=f"{paths[1]} is a symlink to it", fails_when_missing=False, @@ -294,7 +294,7 @@ class Component: substitutions = self._substitutions(script, target) copied = None for line_no, line in enumerate(script.lines[:number], 1): - cp = _split(line.strip().split("&&")[0]) + cp = split(line.strip().split("&&")[0]) if cp and cp[0] == "cp" and cp[-1] == target and "$component_config/" in cp[-2]: copied = (line_no, cp[-2].split("$component_config/", 1)[1]) if copied is None: @@ -422,7 +422,7 @@ class Component: if not _mentions_bios(raw): continue if words[0] == "exec" and len(words) > 1 and _mentions_bios(words[1]): - folder, name = _split_path(words[1]) + folder, name = split_path(words[1]) self.record( "fixed_name", [name], [(path, number)], case_insensitive=False, search_dir=folder, passes_to="exec", fails_when_missing=True, @@ -468,7 +468,7 @@ class Component: n for n, line in enumerate(script.lines, 1) if line.strip().startswith(f"{source.group(1)}=") ) - folder, name = _split_path(destination) + folder, name = split_path(destination) self.record( "fixed_name", [name], [(path, assigned), (path, number), (path, install_line)], case_insensitive=False, search_dir=folder, @@ -492,8 +492,8 @@ def _installs(word: str) -> bool: def _render_targets(names: list[str], targets: list[str]) -> str: """Where copied names land: one folder when each keeps its name, else each path.""" - folders = {_split_path(t)[0] for t in targets} - kept = [_split_path(t)[1] for t in targets] == [PurePosixPath(n).name for n in names] + folders = {split_path(t)[0] for t in targets} + kept = [split_path(t)[1] for t in targets] == [PurePosixPath(n).name for n in names] if kept and len(folders) == 1: return f"{folders.pop()}/" return ", ".join(targets) @@ -512,7 +512,7 @@ def core_options(read: Read) -> list[Launcher]: ] if not copied: raise LauncherPatternMissing(prepare_path, "the core options preset is never copied") - target = _split(prepare.splitlines()[copied[0] - 1].strip())[-1] + target = split(prepare.splitlines()[copied[0] - 1].strip())[-1] records = [] for line_no, line in enumerate(text.splitlines(), 1): found = re.match(r'^([\w.-]+)\s*=\s*"([^"]*)"$', line.strip()) diff --git a/scripts/scraper/retropie_launchers.py b/scripts/scraper/retropie_launchers.py index 7ba6cb3c8..f07b89598 100644 --- a/scripts/scraper/retropie_launchers.py +++ b/scripts/scraper/retropie_launchers.py @@ -23,7 +23,7 @@ import re from pathlib import PurePosixPath from typing import Any -from .retropie_reader import PackageReader, _mentions_bios, _split_path +from .retropie_reader import PackageReader, mentions_bios, split_path from .retropie_scripts import ( Launcher, LauncherPatternMissing, @@ -31,7 +31,7 @@ from .retropie_scripts import ( SCRIPTMODULES, SECTIONS, Scripts, - _VAR, + VAR, merge_records, source_ref, ) @@ -81,7 +81,7 @@ def launch_script_records(scripts: Scripts) -> list[Launcher]: len(parts) == 4 and parts[0] == SCRIPTMODULES and parts[1] in SECTIONS and path.endswith(".sh") ) - if not is_script or not _mentions_bios(text): + if not is_script or not mentions_bios(text): continue package = scripts.modules.get(parts[2]) if package is None: @@ -102,7 +102,7 @@ def _launch_script(path: str, lines: list[str], package: Module) -> list[Launche continue assign = re.match(r'^([A-Za-z_]\w*)="([^"]*)"$', stripped) if assign is not None: - env[assign.group(1)] = _VAR.sub( + env[assign.group(1)] = VAR.sub( lambda m: env.get(m.group(1) or m.group(3), m.group(0)), assign.group(2) ) continue @@ -110,8 +110,8 @@ def _launch_script(path: str, lines: list[str], package: Module) -> list[Launche if check is None: continue tested = check.group(1) - resolved = _VAR.sub(lambda m: env.get(m.group(1) or m.group(3), m.group(0)), tested) - if not _mentions_bios(resolved): + resolved = VAR.sub(lambda m: env.get(m.group(1) or m.group(3), m.group(0)), tested) + if not mentions_bios(resolved): continue block_start = number message: str | None = None @@ -137,7 +137,7 @@ def _launch_script(path: str, lines: list[str], package: Module) -> list[Launche passes_to = f"command line {flag.group(1)}" cited.append(later) break - folder, name = _split_path(resolved) + folder, name = split_path(resolved) records.append(Launcher( emulator=package.id, package=package.id, build=package.build, kind="fixed_name", names=[name], case_insensitive=False, diff --git a/scripts/scraper/retropie_reader.py b/scripts/scraper/retropie_reader.py index 239fa4e88..b17cf2aa4 100644 --- a/scripts/scraper/retropie_reader.py +++ b/scripts/scraper/retropie_reader.py @@ -12,8 +12,8 @@ from .retropie_scripts import ( LauncherPatternMissing, Module, Scripts, - _FUNCTION, - _split, + FUNCTION, + split, source_ref, ) @@ -73,7 +73,7 @@ def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR) ) -def _mentions_bios(text: str) -> bool: +def mentions_bios(text: str) -> bool: return BIOSDIR in text or "${biosdir}" in text or BIOS_SPELLED in text @@ -81,7 +81,7 @@ def _is_file(path: str) -> bool: return bool(_EXTENSION.search(PurePosixPath(path).name)) and "*" not in path -def _split_path(path: str) -> tuple[str, str]: +def split_path(path: str) -> tuple[str, str]: pure = PurePosixPath(path.rstrip("/")) return str(pure.parent), pure.name @@ -146,13 +146,13 @@ class PackageReader: def _classify(self, event: Event) -> None: command = event.words[0][0] if event.heredoc: - if _mentions_bios(event.raw): + if mentions_bios(event.raw): self._heredoc_setting(event) return if command == "addEmulator": self._add_emulator(event) return - if command == "iniSet" and not _mentions_bios(event.raw): + if command == "iniSet" and not mentions_bios(event.raw): # A search path below the roms root: MAME reads its samples from # samplepath $romdir/mame/samples;$romdir/arcade/samples. if _search_list_in_roms( @@ -160,7 +160,7 @@ class PackageReader: ): self._ini_set(event) return - if not _mentions_bios(event.raw): + if not mentions_bios(event.raw): return if command in HOUSEKEEPING: return @@ -186,10 +186,10 @@ class PackageReader: def _is_bios_link(self, event: Event) -> bool: words = event.words - if words[0][0] != "ln" or not _mentions_bios(event.raw): + if words[0][0] != "ln" or not mentions_bios(event.raw): return False paths = [w for w in words[1:] if not w[0].startswith("-")] - if len(paths) != 2 or not all(_mentions_bios(v) for v in paths[0]): + if len(paths) != 2 or not all(mentions_bios(v) for v in paths[0]): raise LauncherPatternMissing( f"{event.path}:{event.line}", f"link without a BIOS source: {event.raw}" ) @@ -210,10 +210,10 @@ class PackageReader: paths = [w for w in event.words[1:] if not w[0].startswith("-")] source, target = paths if len(target) == 1 and len(source) > 1: - target = [f"{target[0].rstrip('/')}/{_split_path(s)[1]}" for s in source] + target = [f"{target[0].rstrip('/')}/{split_path(s)[1]}" for s in source] sources += source targets += target - folders = {_split_path(s)[0] for s in sources} + folders = {split_path(s)[0] for s in sources} whole_dir = all( not _is_file(s) and "/" not in s.replace(BIOSDIR, "", 1).strip("/") for s in sources ) @@ -228,7 +228,7 @@ class PackageReader: "links from several BIOS folders in one run", ) search_dir = folders.pop() - names = [_split_path(s)[1] for s in sources] + names = [split_path(s)[1] for s in sources] passes_to = _render_targets(names, targets) self.record( "links", names, [(e.path, e.line) for e in events], @@ -239,15 +239,15 @@ class PackageReader: def _copy(self, event: Event) -> None: paths = [v for w in event.words[1:] if not w[0].startswith("-") for v in w] *sources, target = paths - if not _mentions_bios(target): + if not mentions_bios(target): raise LauncherPatternMissing( f"{event.path}:{event.line}", f"copy out of the BIOS directory: {event.raw}" ) - folders = {_split_path(s)[0] for s in sources} + folders = {split_path(s)[0] for s in sources} if len(folders) != 1: raise LauncherPatternMissing(f"{event.path}:{event.line}", "copy from several folders") self.record( - "copies", [_split_path(s)[1] for s in sources], [(event.path, event.line)], + "copies", [split_path(s)[1] for s in sources], [(event.path, event.line)], search_dir=folders.pop(), passes_to=target.rstrip("/"), fails_when_missing=False, depends_on_option=self._depends(event), ) @@ -264,7 +264,7 @@ class PackageReader: raise LauncherPatternMissing(f"{event.path}:{event.line}", "unzip without -d") target = values[values.index("-d") + 1] archives = [v for v in values if v.endswith(".zip")] - if len(archives) != 1 or not _mentions_bios(target): + if len(archives) != 1 or not mentions_bios(target): raise LauncherPatternMissing(f"{event.path}:{event.line}", f"unzip of {event.raw}") self.record( "copies", [], [(event.path, event.line)], @@ -274,25 +274,25 @@ class PackageReader: def _move(self, event: Event) -> None: source, target = (w for w in event.words[1:] if not w[0].startswith("-")) - if not all(_mentions_bios(v) for v in source + target): + if not all(mentions_bios(v) for v in source + target): raise LauncherPatternMissing( f"{event.path}:{event.line}", f"move across folders: {event.raw}" ) - folders = {_split_path(s)[0] for s in source} - destinations = {_split_path(t)[0] for t in target} + folders = {split_path(s)[0] for s in source} + destinations = {split_path(t)[0] for t in target} if len(folders) != 1 or len(destinations) != 1: raise LauncherPatternMissing( f"{event.path}:{event.line}", "move between several folders" ) self.record( - "moves", [_split_path(s)[1] for s in source], [(event.path, event.line)], + "moves", [split_path(s)[1] for s in source], [(event.path, event.line)], case_insensitive=False, search_dir=folders.pop(), passes_to=destinations.pop(), fails_when_missing=False, depends_on_option=self._depends(event), ) def _move_dir(self, event: Event) -> None: link, real = (w[0] for w in event.words[1:3]) - if not _mentions_bios(real) or _mentions_bios(link): + if not mentions_bios(real) or mentions_bios(link): raise LauncherPatternMissing( f"{event.path}:{event.line}", f"moveConfigDir into a non-BIOS folder: {event.raw}" ) @@ -307,7 +307,7 @@ class PackageReader: target = self._ini_file(event) passes_to = f"{key} in {self.final(target)}" if target else key if _is_file(value) and ";" not in value: - folder, name = _split_path(value) + folder, name = split_path(value) self.record( "fixed_name", [name], [(event.path, event.line)], case_insensitive=False, search_dir=folder, passes_to=passes_to, @@ -326,21 +326,21 @@ class PackageReader: return event.words[3][0] lines = self.scripts.files[event.path].splitlines() for number in range(event.line - 1, 0, -1): - words = _split(lines[number - 1].strip()) + words = split(lines[number - 1].strip()) if words and words[0] == "iniConfig" and len(words) >= 4: return words[3] - if _FUNCTION.match(lines[number - 1]): + if FUNCTION.match(lines[number - 1]): break return None def _written(self, event: Event) -> None: """A file the package writes into the BIOS directory itself.""" target = next( - (v for w in reversed(event.words[1:]) for v in w if _mentions_bios(v)), None + (v for w in reversed(event.words[1:]) for v in w if mentions_bios(v)), None ) if target is None or not _is_file(target): raise LauncherPatternMissing(f"{event.path}:{event.line}", f"write of {event.raw}") - folder, name = _split_path(target) + folder, name = split_path(target) self.record( "copies", [name], [(event.path, event.line)], search_dir=None, passes_to=folder, @@ -350,7 +350,7 @@ class PackageReader: def _build_flag(self, event: Event) -> None: flags = [ v for w in event.words[1:] for v in w - if v.startswith("-D") and "=" in v and _mentions_bios(v) + if v.startswith("-D") and "=" in v and mentions_bios(v) ] if not flags: raise LauncherPatternMissing(f"{event.path}:{event.line}", f"cmake of {event.raw}") @@ -375,7 +375,7 @@ class PackageReader: key, value = found.group(1), found.group(2) kind, names, folder = "passes_path", [], value if _is_file(value): - folder, name = _split_path(value) + folder, name = split_path(value) kind, names = "fixed_name", [name] written = _redirect_target(event.opener) if written is None: @@ -393,17 +393,17 @@ class PackageReader: if len(event.words) < 5: return command = event.words[4][0] - if not _mentions_bios(command): + if not mentions_bios(command): return names = event.words[2] - tokens = _split(command) + tokens = split(command) found = [ (flag, value) for flag, value in zip(tokens, tokens[1:]) - if flag.startswith("-") and _mentions_bios(value) + if flag.startswith("-") and mentions_bios(value) ] found += [ (head, tail) for head, sep, tail in (token.partition("=") for token in tokens) - if head.startswith("-") and sep and _mentions_bios(tail) + if head.startswith("-") and sep and mentions_bios(tail) ] if not found: raise LauncherPatternMissing( @@ -415,7 +415,7 @@ class PackageReader: self._command_line(event, emulator, flag, value) def _command_line(self, event: Event, emulator: str, flag: str, value: str) -> None: - folder, name = _split_path(value) + folder, name = split_path(value) if _is_file(value): kind, names, search = "fixed_name", [name], folder else: @@ -435,7 +435,7 @@ class PackageReader: for event in events: if event.words[0][0] != "addEmulator" or len(event.words) < 5: continue - tokens = _split(event.words[4][0]) + tokens = split(event.words[4][0]) for flag, value in zip(tokens, tokens[1:]): if flag in flags: seen.add(flag) @@ -474,7 +474,7 @@ class PackageReader: ) for event in events: - if event.heredoc or not event.words or _mentions_bios(event.raw): + if event.heredoc or not event.words or mentions_bios(event.raw): continue command = event.words[0][0] if command == "moveConfigDir" and len(event.words) >= 3: @@ -533,8 +533,8 @@ def _redirect_target(words: list[list[str]]) -> str | None: def _render_targets(names: list[str], targets: list[str]) -> str: """Where linked names land: one folder when the names are kept, each path when renamed.""" - folders = {_split_path(t)[0] for t in targets} - kept = [_split_path(t)[1] for t in targets] == names + folders = {split_path(t)[0] for t in targets} + kept = [split_path(t)[1] for t in targets] == names if kept and len(folders) == 1: return f"{folders.pop()}/" return ", ".join(targets) diff --git a/scripts/scraper/retropie_scripts.py b/scripts/scraper/retropie_scripts.py index c8975bcce..c3074b13a 100644 --- a/scripts/scraper/retropie_scripts.py +++ b/scripts/scraper/retropie_scripts.py @@ -23,12 +23,12 @@ SECTIONS = ("emulators", "libretrocores", "ports") LIBRETRO_FRONTEND = "retroarch" -_FUNCTION = re.compile(r"^function\s+([\w.+-]+)\s*\(\)\s*\{\s*$") +FUNCTION = re.compile(r"^function\s+([\w.+-]+)\s*\(\)\s*\{\s*$") _ASSIGN = re.compile(r"^(?:local\s+)?([A-Za-z_]\w*)=(.*)$") _DECLARE = re.compile(r"^local\s+([A-Za-z_]\w*(?:\s+[A-Za-z_]\w*)*)\s*$") _FOR = re.compile(r"^for\s+([A-Za-z_]\w*)\s+in\s+(.*?)\s*(?:;\s*do)?\s*$") _HEREDOC = re.compile(r"(? list[str]: ] -def _split(text: str) -> list[str]: +def split(text: str) -> list[str]: """Shell words with quotes removed, a line bash itself would accept.""" try: return shlex.split(text, comments=True) @@ -188,7 +188,7 @@ class Scripts: heredoc = _HEREDOC.search(line) if heredoc is not None: tag = heredoc.group(1) - header = _FUNCTION.match(line) + header = FUNCTION.match(line) if header is not None: opened = (header.group(1), number) elif opened is not None and line.rstrip() == "}": @@ -206,7 +206,7 @@ class Scripts: start, end = module.functions[name] body = [line.strip() for line in module.lines[start:end - 1] if line.strip()] if len(body) == 1: - words = _split(body[0]) + words = split(body[0]) if len(words) == 2 and words[0] == "echo": return words[1] return None @@ -250,7 +250,7 @@ class Scripts: events.setdefault((module.path, number), Event( module.path, number, self._expand_all(stripped.split(), package, env), stripped, conditions + self._shown(branches, package, env), True, - self._expand_all(_split(opener), package, env), + self._expand_all(split(opener), package, env), )) continue if not stripped or stripped.startswith("#"): @@ -275,7 +275,7 @@ class Scripts: continue if self._bind(stripped, package, env): continue - words = [self.expand(w, package, env) for w in _split(stripped)] + words = [self.expand(w, package, env) for w in split(stripped)] # The first walk to reach a line is the one with its caller's arguments. events.setdefault( (module.path, number), Event(module.path, number, words, stripped, shown, False) @@ -311,7 +311,7 @@ class Scripts: closed = body.endswith(")") array[1].append(body[:-1] if closed else body) if closed: - words = _split(" ".join(array[1])) + words = split(" ".join(array[1])) env[array[0]] = [v for w in words for v in self.expand(w, package, env)] return closed @@ -322,7 +322,7 @@ class Scripts: """Track for/while/until/done, and say whether the line was one of them.""" loop = _FOR.match(stripped) if loop is not None: - values = [v for w in _split(loop.group(2)) for v in self.expand(w, package, env)] + values = [v for w in split(loop.group(2)) for v in self.expand(w, package, env)] loops.append((loop.group(1), env.get(loop.group(1)))) env[loop.group(1)] = values return True @@ -419,9 +419,9 @@ class Scripts: if value.startswith("("): closing = value.rfind(")") inner = value[1:closing] if closing > 0 else value[1:] - env[name] = [v for w in _split(inner) for v in self.expand(w, package, env)] + env[name] = [v for w in split(inner) for v in self.expand(w, package, env)] return True - words = _split(value) or [""] + words = split(value) or [""] if "$(" in words[0] and _SUBST.fullmatch(words[0]) is None: # A command's output: the variable stays a reference. env.pop(name, None) @@ -444,13 +444,13 @@ class Scripts: word = _SUBST.sub(substitute, word) results: list[str] = [] for braced in _brace(word): - names = [m.group(1) or m.group(3) for m in _VAR.finditer(braced)] + names = [m.group(1) or m.group(3) for m in VAR.finditer(braced)] bound = [n for n in names if n in env] if not bound: results.append(braced) continue results.extend( - _VAR.sub(partial(_bound_value, dict(zip(bound, values))), braced) + VAR.sub(partial(_bound_value, dict(zip(bound, values))), braced) for values in product(*(env[n] for n in bound)) ) return results diff --git a/scripts/scraper/rocknix_configs.py b/scripts/scraper/rocknix_configs.py index 01bd10ab1..b5bd88953 100644 --- a/scripts/scraper/rocknix_configs.py +++ b/scripts/scraper/rocknix_configs.py @@ -131,7 +131,7 @@ def per_device( ] -def _file_under(value: str, root: str) -> bool: +def file_under(value: str, root: str) -> bool: return value.startswith(root.rstrip("/") + "/") @@ -141,7 +141,7 @@ def bios_keys(tree: RepoTree, paths: list[str], root: str = BIOS_ROOT) -> list[t for path in paths: for setting in settings(tree.read(path)): key = (setting.section, setting.key) - if _file_under(setting.value, root) and key not in keys: + if file_under(setting.value, root) and key not in keys: keys.append(key) if not keys: raise LauncherPatternMissing(paths[0], f"key naming a file under {root}") @@ -171,7 +171,7 @@ def with_evidence( return apply_evidence(record, placements) -def _keys(value: FixedPaths) -> list[str]: +def fixed_path_keys(value: FixedPaths) -> list[str]: return [f"[{section}] {key}" if section else key for section, key in value.keys] @@ -226,7 +226,7 @@ def config_records( depends_on_option=depends_on_option, ), installed.target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}", - _keys(value), + fixed_path_keys(value), installed.start, )) return records diff --git a/scripts/scraper/rocknix_launchers.py b/scripts/scraper/rocknix_launchers.py index 019956dff..bf3b6aa8b 100644 --- a/scripts/scraper/rocknix_launchers.py +++ b/scripts/scraper/rocknix_launchers.py @@ -34,8 +34,8 @@ from .rocknix_configs import ( Installed, RETROARCH, STANDALONE, - _file_under, - _keys, + file_under, + fixed_path_keys, config_records, device_configs, directory_records, @@ -121,7 +121,7 @@ def amiberry(tree: RepoTree) -> list[Launcher]: Setting(s.section, s.key, s.value.replace(sed.group(1), root), s.line) for s in settings(tree.read(path)) ] - keys = [(s.section, s.key) for s in found if _file_under(s.value, root)] + keys = [(s.section, s.key) for s in found if file_under(s.value, root)] if not keys: raise LauncherPatternMissing(path, f"key naming a file under {sed.group(1)}") value, lines = fixed_paths(found, keys, path) @@ -140,7 +140,7 @@ def amiberry(tree: RepoTree) -> list[Launcher]: depends_on_option=f"{condition}, {content}", ), target, - _keys(value), + fixed_path_keys(value), script, source_name=config, )) @@ -191,7 +191,7 @@ def hatari(tree: RepoTree) -> list[Launcher]: run_line, _ = script.find(r"--configfile", "--configfile", copy_line) path = f"{package}/config/conf/{copy.group(1)}" found = settings(tree.read(path)) - keys = [(s.section, s.key) for s in found if _file_under(s.value, BIOS_ROOT)] + keys = [(s.section, s.key) for s in found if file_under(s.value, BIOS_ROOT)] if not keys: raise LauncherPatternMissing(path, f"key naming a file under {BIOS_ROOT}") value, lines = fixed_paths(found, keys, path) @@ -210,7 +210,7 @@ def hatari(tree: RepoTree) -> list[Launcher]: passes_to=f"{describe_keys(copy.group(1), value.keys)} (--configfile)", ), script.expand(copied.group(1), copy_line, set()), - _keys(value), + fixed_path_keys(value), script, source_name=copy.group(1), )] @@ -293,7 +293,7 @@ def nanoboyadvance(tree: RepoTree) -> list[Launcher]: package = f"{STANDALONE}/nanoboyadvance-sa" path = f"{package}/config/config.toml" found = settings(tree.read(path)) - keys = [(s.section, s.key) for s in found if _file_under(s.value, BIOS_ROOT)] + keys = [(s.section, s.key) for s in found if file_under(s.value, BIOS_ROOT)] if not keys: raise LauncherPatternMissing(path, f"key naming a file under {BIOS_ROOT}") value, lines = fixed_paths(found, keys, path) @@ -317,7 +317,7 @@ def nanoboyadvance(tree: RepoTree) -> list[Launcher]: fails_when_missing=True, ), f"{CONFIG_ROOT}/nanoboyadvance/config.toml", - _keys(value), + fixed_path_keys(value), Script(start_path, tree.read(start_path)), )] diff --git a/scripts/scraper/romfolders/es.py b/scripts/scraper/romfolders/es.py index 96f74700d..bceb0a2b5 100644 --- a/scripts/scraper/romfolders/es.py +++ b/scripts/scraper/romfolders/es.py @@ -34,12 +34,12 @@ from model.safeparse import parse_untrusted_xml, yaml_load_upstream from . import Fetcher, SourceError, register -def _board(core: str | None, emulator: str | None, source_ref: str) -> dict: +def board_entry(core: str | None, emulator: str | None, source_ref: str) -> dict: out = {"core": core or emulator, "emulator": emulator, "source_ref": source_ref} return {k: str(v) for k, v in out.items() if v} -def _offers(choices: list[dict], core: str | None, emulator: str | None) -> list[dict]: +def folder_offers(choices: list[dict], core: str | None, emulator: str | None) -> list[dict]: """Every (emulator, core) a folder can start, in the list's order, or none when the default is the only one. @@ -87,7 +87,7 @@ def _top_key_lines(text: str) -> dict[str, int]: return out -def _strip_prefix(path: str, prefixes: list[str]) -> str | None: +def strip_prefix(path: str, prefixes: list[str]) -> str | None: """The folder under the roms root, or None for a path outside it.""" for prefix in prefixes: if path.startswith(prefix): @@ -96,7 +96,7 @@ def _strip_prefix(path: str, prefixes: list[str]) -> str | None: return None -def _extensions(raw: str | list | None) -> list[str]: +def extension_list(raw: str | list | None) -> list[str]: words = raw.split() if isinstance(raw, str) else [str(w) for w in raw or []] return [w if w.startswith(".") else f".{w}" for w in words if w] @@ -163,14 +163,14 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]: override = data.get(name) or {} b_emu, b_core = override.get("emulator", emulator), override.get("core", core) if (b_emu, b_core) != (emulator, core) and b_core: - board_defaults[board] = _board(b_core, b_emu, format_ref(key, real, lines.get(name))) + board_defaults[board] = board_entry(b_core, b_emu, format_ref(key, real, lines.get(name))) refs = [format_ref(key, es_path, es_lines.get(name))] if name in def_lines: refs.append(format_ref(key, def_path, def_lines[name])) rows.append({ "folder": str(folder), "name": name, - "extensions": _extensions(system.get("extensions")), + "extensions": extension_list(system.get("extensions")), "core": str(core) if core else None, "emulator": str(emulator) if emulator else None, "source_ref": "; ".join(refs), @@ -184,7 +184,7 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]: # Static es_systems.cfg (XML) and EmuELEC's es_systems.json -def _first_lines(text: str, pattern: str) -> dict[str, int]: +def first_lines(text: str, pattern: str) -> dict[str, int]: out: dict[str, int] = {} for number, line in enumerate(text.splitlines(), 1): match = re.search(pattern, line) @@ -261,7 +261,7 @@ def es_xml(spec: dict, fetcher: Fetcher) -> list[dict]: for row in rows: alt = other.get(row["name"]) if alt and alt["core"] and (alt["core"], alt["emulator"]) != (row["core"], row["emulator"]): - row.setdefault("board_defaults", {})[board] = _board( + row.setdefault("board_defaults", {})[board] = board_entry( alt["core"], alt["emulator"], alt["source_ref"]) return rows @@ -270,7 +270,7 @@ _BARE_AMPERSAND = re.compile(r"&(?!(?:[A-Za-z]+|#\d+|#x[0-9A-Fa-f]+);)") _COMMENT = re.compile(r"", re.DOTALL) -def _lenient_xml(text: str) -> str: +def lenient_xml(text: str) -> str: """The list as EmulationStation's pugixml reads it, lines kept in place. pugixml keeps a bare `&` as text (ArkOS ships `2>&1` in a command) and @@ -283,7 +283,7 @@ def _lenient_xml(text: str) -> str: def _xml_rows(text: str, key: str, path: str, params: dict) -> list[dict]: - text = _lenient_xml(text) + text = lenient_xml(text) root = parse_untrusted_xml(text, path) lines = _all_lines(text, r"([^<]+)") seen: dict[str, int] = {} @@ -296,7 +296,7 @@ def _xml_rows(text: str, key: str, path: str, params: dict) -> list[dict]: row = _name_once({"name": name}, lines, seen) if not name or "ignore" in (command, platform): continue - folder = _strip_prefix((system.findtext("path") or "").strip(), params["path_prefixes"]) + folder = strip_prefix((system.findtext("path") or "").strip(), params["path_prefixes"]) if not folder: continue emulators = [ @@ -313,11 +313,11 @@ def _xml_rows(text: str, key: str, path: str, params: dict) -> list[dict]: rows.append({ "folder": folder, "name": row["name"], - "extensions": _extensions(system.findtext("extension")), + "extensions": extension_list(system.findtext("extension")), "core": core or emulator, "emulator": emulator, "source_ref": format_ref(key, path, row["line"]), - "offers": _offers( + "offers": folder_offers( [{"emulator": e, "core": c} for e, cores in emulators for c, _d in cores or [(e, False)]], core, emulator), "arcade": _is_arcade(system.findtext("hardware"), platform), @@ -340,7 +340,7 @@ def es_json(spec: dict, fetcher: Fetcher) -> list[dict]: row = _name_once({"name": name}, lines, seen) if "ignore" in (system.get("command"), system.get("platform")): continue - folder = _strip_prefix(system.get("path") or "", params["path_prefixes"]) + folder = strip_prefix(system.get("path") or "", params["path_prefixes"]) if not name or not folder: continue emulators = [ @@ -352,11 +352,11 @@ def es_json(spec: dict, fetcher: Fetcher) -> list[dict]: rows.append({ "folder": folder, "name": row["name"], - "extensions": _extensions(system.get("extensions")), + "extensions": extension_list(system.get("extensions")), "core": core or emulator, "emulator": emulator, "source_ref": format_ref(key, path, row["line"]), - "offers": _offers( + "offers": folder_offers( [{"emulator": e, "core": c} for e, cores in emulators for c, _d in cores or [(e, False)]], core, emulator), "arcade": _is_arcade(system.get("hardware"), system.get("platform")), diff --git a/scripts/scraper/romfolders/esde.py b/scripts/scraper/romfolders/esde.py index 5a638a844..b3dda30de 100644 --- a/scripts/scraper/romfolders/esde.py +++ b/scripts/scraper/romfolders/esde.py @@ -10,7 +10,7 @@ from model.romfolders import format_ref from model.safeparse import parse_untrusted_xml from . import Fetcher, SourceError, register -from .es import _extensions, _first_lines, _lenient_xml, _offers, _strip_prefix +from .es import extension_list, first_lines, lenient_xml, folder_offers, strip_prefix # --------------------------------------------------------------------------- @@ -33,13 +33,13 @@ def command_core(command: str) -> tuple[str | None, str | None]: def esde_systems(text: str, path: str) -> Iterator[tuple[str, str, list[str], list[tuple[str, str]]]]: - root = parse_untrusted_xml(_lenient_xml(text), path) + root = parse_untrusted_xml(lenient_xml(text), path) for system in root.iter("system"): name = (system.findtext("name") or "").strip() rom_path = (system.findtext("path") or "").strip() commands = [((c.get("label") or "").strip(), (c.text or "").strip()) for c in system.findall("command")] - yield name, rom_path, _extensions(system.findtext("extension")), commands + yield name, rom_path, extension_list(system.findtext("extension")), commands def _alternative_emulators(text: str, function: str) -> dict[str, tuple[str, int]]: @@ -116,7 +116,7 @@ def _searched_by(commands: list[tuple[str, str, int | None]], key: str, path: st continue reads = [ folder for part in words[at + 1].split(";") - if (folder := _strip_prefix(part, ["%ROMPATH%/", "%ROMPATH%\\"])) + if (folder := strip_prefix(part, ["%ROMPATH%/", "%ROMPATH%\\"])) ] if not reads: continue @@ -167,11 +167,11 @@ def esde(spec: dict, fetcher: Fetcher) -> list[dict]: systems: dict[str, dict] = {} for item in [params["systems"], *params.get("custom", [])]: key, path = item["source"], item["path"] - text = _lenient_xml(fetcher.text(key, path)) - lines = _first_lines(text, r"([^<]+)") + text = lenient_xml(fetcher.text(key, path)) + lines = first_lines(text, r"([^<]+)") command_lines = _command_lines(text) for name, rom_path, extensions, commands in esde_systems(text, path): - folder = _strip_prefix(rom_path, ["%ROMPATH%/", "%ROMPATH%\\"]) + folder = strip_prefix(rom_path, ["%ROMPATH%/", "%ROMPATH%\\"]) if not name or not folder: continue start = lines.get(name) or 0 @@ -207,7 +207,7 @@ def esde(spec: dict, fetcher: Fetcher) -> list[dict]: else: note = f"alternative emulator '{label}' names no command of this system" emulator, core = command_core(chosen[1]) - offers = _offers([ + offers = folder_offers([ {"emulator": e, "core": c, "source_ref": format_ref(key_, path_, line)} for _label, command, line, key_, path_ in system["placed"] for e, c in [command_core(command)] if e diff --git a/scripts/scraper/romfolders/packages.py b/scripts/scraper/romfolders/packages.py index aac2850b1..87281f36c 100644 --- a/scripts/scraper/romfolders/packages.py +++ b/scripts/scraper/romfolders/packages.py @@ -12,7 +12,7 @@ from model.romfolders import DEFAULT_ROW_SOURCE, format_ref from ..recalbox_romfs import Defconfig, defconfig_boards, read_system_ini from ..retropie_modules import PLATFORM_FLAGS, module_enabled, module_fields from . import Fetcher, SourceError, register -from .es import _board, _extensions, _offers, _strip_prefix +from .es import board_entry, extension_list, folder_offers, strip_prefix # --------------------------------------------------------------------------- @@ -134,7 +134,7 @@ def elec_conf(spec: dict, fetcher: Fetcher) -> list[dict]: if conf_text is None: continue values, value_lines = _conf_values(conf_text) - folder = _strip_prefix(values.get("SYSTEM_PATH", ""), params["path_prefixes"]) + folder = strip_prefix(values.get("SYSTEM_PATH", ""), params["path_prefixes"]) if not folder: continue mine = [c for c in cores if c["system"] == name] @@ -150,7 +150,7 @@ def elec_conf(spec: dict, fetcher: Fetcher) -> list[dict]: board = _board_key(c["branches"]) if c is not pick and board and (c["emulator"], c["core"]) != ( pick and pick["emulator"], pick and pick["core"]): - board_defaults[board] = _board(c["core"], c["emulator"], format_ref(key, package, c["line"])) + board_defaults[board] = board_entry(c["core"], c["emulator"], format_ref(key, package, c["line"])) refs = [ format_ref(key, conf_path, value_lines.get("SYSTEM_PATH"), value_lines.get("SYSTEM_EXTENSION")), format_ref(key, package, *lines), @@ -164,12 +164,12 @@ def elec_conf(spec: dict, fetcher: Fetcher) -> list[dict]: rows.append({ "folder": folder, "name": name, - "extensions": _extensions(values.get("SYSTEM_EXTENSION")), + "extensions": extension_list(values.get("SYSTEM_EXTENSION")), "core": pick["core"] if pick else None, "emulator": pick["emulator"] if pick else None, "source_ref": "; ".join(refs), "board_defaults": board_defaults, - "offers": _offers([ + "offers": folder_offers([ {"emulator": c["emulator"], "core": c["core"], "when": ", ".join(f"{v} {p}".strip() for v, p in c["branches"]), "source_ref": format_ref(key, package, c["line"])} @@ -235,7 +235,7 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]: ini = read_system_ini(text) sections, lines = ini.sections, ini.lines system = sections.get("system", {}) - folder = _strip_prefix(system.get("roms.folder", ""), ["%ROOT%/"]) + folder = strip_prefix(system.get("roms.folder", ""), ["%ROOT%/"]) if not folder: continue picks: dict[str, dict] = {} @@ -272,7 +272,7 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]: core, emulator = max(shared, key=lambda pair: shared[pair]) first = next(pick for pick in picks.values() if (pick["core"], pick["emulator"]) == (core, emulator)) board_defaults = { - board: _board(pick["core"], pick["emulator"], pick["source_ref"]) + board: board_entry(pick["core"], pick["emulator"], pick["source_ref"]) for board, pick in picks.items() if (pick["core"], pick["emulator"]) != (core, emulator) } archive = any(e.endswith("!") for e in extensions) @@ -380,7 +380,7 @@ def retropie(spec: dict, fetcher: Fetcher) -> list[dict]: emulator = "retroarch" if core and core.startswith("lr-") else core rows.append({ "folder": system, - "extensions": _extensions(raw), + "extensions": extension_list(raw), "core": core, "emulator": emulator, "source_ref": "; ".join(refs), diff --git a/tests/test_audit_cli.py b/tests/test_audit_cli.py index c0e054f66..ebcfbb339 100644 --- a/tests/test_audit_cli.py +++ b/tests/test_audit_cli.py @@ -1204,13 +1204,13 @@ class HashInputNamesWhatItAccepts(unittest.TestCase): def test_the_truth_anchors_a_sha256_only_entry(self): """rust_dos and ares name files by sha256 alone: the truth left their md5 empty, so md5 platforms never received them.""" - from scripts.resolve.truthsystems import _enrich_hashes + from scripts.resolve.truthsystems import enrich_hashes db = {"files": {"s" * 40: {"sha1": "s" * 40, "md5": "m" * 32, "sha256": "f" * 64, "crc32": "0badf00d", "size": 16}}, "indexes": {"by_sha256": {"f" * 64: "s" * 40}}} entry = {"name": "5200.rom", "sha256": "F" * 64} - _enrich_hashes(entry, db) + enrich_hashes(entry, db) self.assertEqual((entry["md5"], entry["sha1"], entry["size"]), ("m" * 32, "s" * 40, 16)) diff --git a/tests/test_hash_merge.py b/tests/test_hash_merge.py index d0f05c1d4..55b20e853 100644 --- a/tests/test_hash_merge.py +++ b/tests/test_hash_merge.py @@ -255,7 +255,7 @@ class TestMameMerge(unittest.TestCase): The manager set loads "01", but written unquoted it re-parses as the integer 1 and the profile stops naming the file the driver opens. """ - from scripts.scraper._hash_write import _append_new_entries, _format_contents + from scripts.scraper._hash_write import _append_new_entries, format_contents contents = [ {"name": "01", "description": "ROM bank 0-1", "size": 8192, @@ -264,7 +264,7 @@ class TestMameMerge(unittest.TestCase): "crc32": "46489d88"}, ] document = yaml.safe_load( - "files:\n - name: manager.zip\n" + _format_contents(contents) + "files:\n - name: manager.zip\n" + format_contents(contents) ) names = [rom["name"] for rom in document["files"][0]["contents"]] self.assertEqual(names, ["01", "23"]) diff --git a/tests/test_launcher_evidence.py b/tests/test_launcher_evidence.py index 15e31d514..6df45f81a 100644 --- a/tests/test_launcher_evidence.py +++ b/tests/test_launcher_evidence.py @@ -27,7 +27,7 @@ from resolve.launcherconfig import ( ) from resolve.launchers import handed_directories from resolve.launcherplaces import launcher_places -from profiling.reportinputs import _check_build_refs +from profiling.reportinputs import check_build_refs from profiling.repos import shipped_build_holders from scraper.retrobat_launchers import _choices_apart from scraper.shell_launchers import LauncherPatternMissing, Script, config_placement @@ -372,7 +372,7 @@ class BuildRefs(unittest.TestCase): asked.append((revision, path)) return ["line"] * 5 if path == "src/a.c" else None - rows = _check_build_refs( + rows = check_build_refs( document, [(Citation("src/a.c:2", "c"), document["config_reads"][0]), (Citation("src/a.c:9, ROCKNIX x.patch:1", "k"), document["config_reads"][0])], @@ -404,7 +404,7 @@ class BuildRefs(unittest.TestCase): asked.append(path) return None - rows = _check_build_refs( + rows = check_build_refs( {"config_reads": [read]}, [(Citation("SSF.exe 0x10-0x20"), read), (Citation("src/a.c:3"), read)], [View()], fetch, diff --git a/tests/test_launchers_retrobat_files.py b/tests/test_launchers_retrobat_files.py index 62646b331..926f958f1 100644 --- a/tests/test_launchers_retrobat_files.py +++ b/tests/test_launchers_retrobat_files.py @@ -22,7 +22,7 @@ from scraper.retrobat_config_files import ( desmume, ) from scraper.retrobat_config_folders import eka2l1, tsugaru, dosbox_copies -from scraper.retrobat_render import _render +from scraper.retrobat_render import render from scraper.retrobat_xbox import CXBX_DATA_FOLDER, cxbx, xemu_saves from scraper.csharp_source import LauncherPatternMissing, Source from tests.launchersretrobatsupport import G, _sources @@ -782,7 +782,7 @@ class EveryBiosReferenceIsRead(unittest.TestCase): "x.cs", 'void f(string rom)\n{\n string p = AppConfig.GetFullPath("bios") + ";" + Path.GetDirectoryName(rom);\n}\n', ) - self.assertEqual(_render(src, "p", 0, len(src.text))[0], "bios;") + self.assertEqual(render(src, "p", 0, len(src.text))[0], "bios;") if __name__ == "__main__": diff --git a/tests/test_standalone_links.py b/tests/test_standalone_links.py index a8f60fd00..b2490991c 100644 --- a/tests/test_standalone_links.py +++ b/tests/test_standalone_links.py @@ -552,7 +552,7 @@ class Scrapers(unittest.TestCase): def test_retrobat_bios_path_setting(self) -> None: from scraper import retrobat_generators - from scraper.retrobat_config_files import _value_writes + from scraper.retrobat_config_files import value_writes from scraper.csharp_source import Source path = f"{retrobat_generators.GENERATORS}/Flycast.Generator.cs" @@ -568,7 +568,7 @@ class Scrapers(unittest.TestCase): } } """) - records = _value_writes(Source(path, text), "flycast", "standalone") + records = value_writes(Source(path, text), "flycast", "standalone") self.assertEqual([r["search_dir"] for r in records], ["bios/dc"]) self.assertIn("Dreamcast.BiosPath", records[0]["passes_to"]) diff --git a/tests/test_truth_layout.py b/tests/test_truth_layout.py index dcadb7c4d..b0b16c58c 100644 --- a/tests/test_truth_layout.py +++ b/tests/test_truth_layout.py @@ -338,16 +338,16 @@ class ASizeOutsideARangeIsAnotherFile(unittest.TestCase): def test_exact_sizes_and_a_window_admit_both(self): """An entry admits its exact sizes and the window declared beside them, as size_refusal reads it. Two windows with no common size clash.""" - from resolve.truthsystems import _sizes_clash + from resolve.truthsystems import sizes_clash disk = {"size": [143360, 143403, 143488], "min_size": 143105, "max_size": 143364} - self.assertFalse(_sizes_clash(disk, {"size": 143200})) - self.assertFalse(_sizes_clash(disk, {"size": 143488})) - self.assertTrue(_sizes_clash(disk, {"size": 143400})) - self.assertFalse(_sizes_clash(disk, {"min_size": 143300, "max_size": 143500})) - self.assertTrue(_sizes_clash({"min_size": 12288, "max_size": 16384}, + self.assertFalse(sizes_clash(disk, {"size": 143200})) + self.assertFalse(sizes_clash(disk, {"size": 143488})) + self.assertTrue(sizes_clash(disk, {"size": 143400})) + self.assertFalse(sizes_clash(disk, {"min_size": 143300, "max_size": 143500})) + self.assertTrue(sizes_clash({"min_size": 12288, "max_size": 16384}, {"min_size": 32768})) - self.assertFalse(_sizes_clash({"min_size": 12288}, {"name": "unsized"})) + self.assertFalse(sizes_clash({"min_size": 12288}, {"name": "unsized"})) class TruthRecordsWhoOpensByName(unittest.TestCase): diff --git a/tests/test_tui_packs.py b/tests/test_tui_packs.py index 75ad4d144..baaf36126 100644 --- a/tests/test_tui_packs.py +++ b/tests/test_tui_packs.py @@ -403,7 +403,7 @@ class PacksWordingAndDocs(unittest.TestCase): self.assertIn("BIOS folder:", menu) self.assertIn("f) copy from a folder or an old card", menu) # The owner's request of 2026-10-27: game data counted apart, g. - # test_doc_pages checks that the figures add up. + # test_doc_pages_installer checks that the figures add up. self.assertRegex(menu, r"\d+ BIOS files \([\d.]+ [KMG]B\)(,| and) \d+ game data files") self.assertRegex(menu, r"g\) Game data: kept \(\d+ files") env = page[page.index("## Environment overrides"):]