refactor: public names for cross-module reads

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 22:59:51 +01:00
1 parent f371790dc6
commit 3853ca2f1c
254 files changed
+2955 -2969

No files matched your search

+2 -2
View File
@@ -31,7 +31,7 @@ def path_history(repo: upstream.Repo, path: str, cache_dir: str) -> list[str]:
"""Commits that touched a path, newest first."""
shas: list[str] = []
for page in range(1, MAX_PAGES + 1):
payload = upstream._api(_history_url(repo, path, page), cache_dir, False,
payload = upstream.cached_api(_history_url(repo, path, page), cache_dir, False,
max_age=upstream.MOVING_TTL)
if not isinstance(payload, list) or not payload:
break
@@ -47,7 +47,7 @@ def find_revision(
"""The newest revision whose copy of the path has this md5, and its bytes."""
wanted = md5.lower()
for sha in path_history(repo, path, cache_dir):
data = upstream._fetch(upstream.content_url(repo, sha, path))
data = upstream.fetch_body(upstream.content_url(repo, sha, path))
if data is not None and hashlib.md5(data).hexdigest() == wanted:
return sha, data
return None
+4 -3
View File
@@ -25,7 +25,8 @@ import argparse
import sys
from core.artifacts import write_text_atomic
from installer_build.amalgamate import BuildError, COMMAND, OUTPUT, PACKAGE, ROOT, build
from installer_build.amalgamate import BuildError, COMMAND, OUTPUT, PACKAGE, build
from core.paths import REPO_ROOT
def main(argv: list[str] | None = None) -> int:
@@ -34,11 +35,11 @@ def main(argv: list[str] | None = None) -> int:
help="write nothing, exit 1 if install.py differs from what the package builds")
args = parser.parse_args(argv)
try:
text = build(ROOT / PACKAGE)
text = build(REPO_ROOT / PACKAGE)
except BuildError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
target = ROOT / OUTPUT
target = REPO_ROOT / OUTPUT
current = target.read_text(encoding="utf-8") if target.exists() else ""
if args.check:
if current != text:
+9 -9
View File
@@ -402,7 +402,7 @@ def check_emulatorjs(platforms_dir: Path, offline: bool) -> Finding:
tag = str((yaml_load(fh) or {}).get("version", ""))
for path in ROMM_DOCKERFILES:
try:
text = upstream._http_text(
text = upstream.http_text(
f"https://raw.githubusercontent.com/rommapp/romm/{tag}/{path}")
except upstream.UpstreamError as exc:
return Finding("platforms", subject, UNKNOWN, local=local, detail=str(exc))
@@ -879,7 +879,7 @@ def core_info_blobs(cache_dir: str, offline: bool) -> dict[str, str] | None:
repo = upstream.parse_repo(CORE_INFO_REPO)
if repo is None:
return None
payload = upstream._api(
payload = upstream.cached_api(
f"{repo.api_base}/repos/{repo.slug}/contents?per_page=100",
cache_dir,
offline,
@@ -1097,7 +1097,7 @@ def _game_catalogs(source: str) -> list[dict]:
def _no_intro_asset_date(cache_dir: str, offline: bool) -> str:
"""The day the mirror last rebuilt its No-Intro pack, empty if unlisted."""
repo = upstream.parse_repo(NO_INTRO_MIRROR)
payload = upstream._api(
payload = upstream.cached_api(
f"{repo.api_base}/repos/{repo.slug}/releases/tags/{NO_INTRO_RELEASE}",
cache_dir,
offline,
@@ -1149,8 +1149,8 @@ def redump_datfile_version(code: str) -> str:
request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "retrobios/1.0"})
with urllib.request.urlopen(request, timeout=60) as response:
disposition = response.headers.get("Content-Disposition", "")
named = game_dat_importer._DISPOSITION.search(disposition)
match = game_dat_importer._REDUMP_FILE.match(named["file"]) if named else None
named = game_dat_importer.DISPOSITION.search(disposition)
match = game_dat_importer.REDUMP_FILE.match(named["file"]) if named else None
if not match:
raise ValueError(f"{url} names no datfile")
return f"{match['date']} {match['time']}"
@@ -1228,7 +1228,7 @@ def _check_tosec(offline: bool) -> Finding:
if offline:
return Finding("catalogs", "tosec", SKIPPED, local=imported, detail="offline")
try:
html = upstream._http_text(TOSEC_DOWNLOADS)
html = upstream.http_text(TOSEC_DOWNLOADS)
except upstream.UpstreamError as exc:
return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail=str(exc))
latest = tosec_latest_pack(html or "")
@@ -1300,7 +1300,7 @@ def _check_fbneo(cache_dir: str, offline: bool) -> Finding:
if offline:
return Finding("catalogs", "fbneo recipes", SKIPPED, local=imported, detail="offline")
repo = upstream.parse_repo(FBNEO_REPO)
listing = upstream._api(
listing = upstream.cached_api(
f"{repo.api_base}/repos/{repo.slug}/contents/dats",
cache_dir,
offline,
@@ -1389,7 +1389,7 @@ def specifier_allows(spec: str, version: str) -> bool:
def pypi_latest(name: str) -> str | None:
payload = upstream._http_json(PYPI_URL.format(name=name))
payload = upstream.http_json(PYPI_URL.format(name=name))
if not isinstance(payload, dict):
return None
info = payload.get("info") or {}
@@ -1406,7 +1406,7 @@ def parse_npm_pins(text: str) -> dict[str, str]:
def npm_latest(name: str) -> str | None:
payload = upstream._http_json(NPM_URL.format(name=name))
payload = upstream.http_json(NPM_URL.format(name=name))
if not isinstance(payload, dict):
return None
return str(payload.get("version") or "") or None
+1 -1
View File
@@ -23,7 +23,7 @@ def toc_slug(text: str) -> str:
return re.sub(r"[-\s]+", "-", text)
def _unique(ident: str, used: set[str]) -> str:
def unique_anchor(ident: str, used: set[str]) -> str:
while ident in used or not ident:
match = IDCOUNT.match(ident)
ident = f"{match[1]}_{int(match[2]) + 1}" if match else f"{ident}_1"
+1 -1
View File
@@ -355,7 +355,7 @@ def repository_output_lock(path: str) -> contextlib.AbstractContextManager[None]
return contextlib.nullcontext()
def _build_timestamp(db: dict | None = None) -> str:
def build_timestamp(db: dict | None = None) -> str:
"""Timestamp for generated artifacts.
Reads the database snapshot the artifact was built from, so rebuilding
+3 -3
View File
@@ -375,7 +375,7 @@ def verify_otp(
Returns (valid, reason_string).
"""
from core.sect233r1 import _N, _ec_mul, _Gx, _Gy, ecdsa_verify_sha256
from core.sect233r1 import N, ec_mul, Gx, Gy, ecdsa_verify_sha256
data = bytearray(Path(filepath).read_bytes())
@@ -436,10 +436,10 @@ def verify_otp(
signature_rs = bytes(data[0x44:0x80])
# Fix up private key: privkey % subgroup_order (Nintendo's ECC lib quirk)
priv_key_int = int.from_bytes(priv_key_raw, "big") % _N
priv_key_int = int.from_bytes(priv_key_raw, "big") % N
# Derive public key from private key: Q = privkey * G
pub_point = _ec_mul(priv_key_int, (_Gx, _Gy))
pub_point = ec_mul(priv_key_int, (Gx, Gy))
if pub_point is None:
return False, "ECC cert: derived public key is point at infinity"
pub_key_xy = pub_point[0].to_bytes(30, "big") + pub_point[1].to_bytes(30, "big")
+2 -2
View File
@@ -21,7 +21,7 @@ import zipfile
from pathlib import Path
# Fixed metadata for deterministic ZIPs
_FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp
FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp
_FIXED_CREATE_SYSTEM = 0 # FAT/DOS (most compatible)
_FIXED_EXTERNAL_ATTR = 0o100644 << 16 # -rw-r--r--
_COMPRESS_LEVEL = 9 # deflate level 9 for determinism
@@ -65,7 +65,7 @@ def rebuild_zip_deterministic(
) as dst:
for info in entries:
out_info = zipfile.ZipInfo(
filename=info.filename, date_time=_FIXED_DATE_TIME
filename=info.filename, date_time=FIXED_DATE_TIME
)
out_info.compress_type = zipfile.ZIP_DEFLATED
out_info.create_system = _FIXED_CREATE_SYSTEM
+5 -5
View File
@@ -7,7 +7,7 @@ import subprocess
def _git_lines(*args: str) -> list[str] | None:
def git_lines(*args: str) -> list[str] | None:
"""Output lines of a git command, or None when git refuses it."""
result = subprocess.run(["git", *args], capture_output=True, text=True, check=False)
if result.returncode != 0:
@@ -27,7 +27,7 @@ def _repo_key(url: str) -> str:
return "/".join(re.split(r"[/:]", path)[-2:]).casefold()
def _project_main_line() -> str | None:
def project_main_line() -> str | None:
"""The project's main line, fetched when this clone does not hold it.
A fork's clone has origin alone. Once the commit is pushed to the fork's
@@ -37,15 +37,15 @@ def _project_main_line() -> str | None:
None leaves the upstream/ and origin/ lines in charge when the clone has
no remote at all and only its uncommitted files can be read.
"""
remotes = _git_lines("remote") or []
remotes = git_lines("remote") or []
if not remotes:
return None
project = {_repo_key(url) for url in PROJECT_URLS}
source = PROJECT_URLS[0]
for remote in remotes:
urls = _git_lines("remote", "get-url", "--all", remote) or []
urls = git_lines("remote", "get-url", "--all", remote) or []
if any(_repo_key(url) in project for url in urls):
if _git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"):
if git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"):
return f"{remote}/main"
source = remote
break
+12 -12
View File
@@ -22,12 +22,12 @@ _F = (1 << 233) | (1 << 74) | 1 # irreducible polynomial
_A = 1
_B = 0x0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD
_Gx = 0x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B
_Gy = 0x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052
Gx = 0x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B
Gy = 0x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052
# Subgroup order
_N = 0x01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7
_N_BITLEN = _N.bit_length() # 233
N = 0x01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7
_N_BITLEN = N.bit_length() # 233
# Cofactor
_H = 2
@@ -156,7 +156,7 @@ def _ec_double(p: tuple[int, int] | None) -> tuple[int, int] | None:
return (x3, y3)
def _ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None:
def ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None:
"""Scalar multiplication k*P using double-and-add."""
if k == 0 or p is _INF:
return _INF
@@ -220,7 +220,7 @@ def ecdsa_verify_sha256(
q_point = (qx, qy)
# Check r, s in [1, n-1]
if not (1 <= r < _N and 1 <= s < _N):
if not (1 <= r < N and 1 <= s < N):
return False
h = hashlib.sha256(message).digest()
@@ -230,20 +230,20 @@ def ecdsa_verify_sha256(
e >>= 256 - _N_BITLEN
# w = s^(-1) mod n
w = _modinv(s, _N)
w = _modinv(s, N)
# u1 = e*w mod n, u2 = r*w mod n
u1 = (e * w) % _N
u2 = (r * w) % _N
u1 = (e * w) % N
u2 = (r * w) % N
# R = u1*G + u2*Q
g_point = (_Gx, _Gy)
r_point = _ec_add(_ec_mul(u1, g_point), _ec_mul(u2, q_point))
g_point = (Gx, Gy)
r_point = _ec_add(ec_mul(u1, g_point), ec_mul(u2, q_point))
if r_point is _INF:
return False
# v = R.x (as integer, already in GF(2^m) which is an integer)
v = r_point[0] % _N
v = r_point[0] % N
return v == r
+46 -46
View File
@@ -311,7 +311,7 @@ def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None:
return RATE_LIMIT_WAITS[waited]
def _fetch(url: str, accept_json: bool = False) -> bytes | None:
def fetch_body(url: str, accept_json: bool = False) -> bytes | None:
"""Body of a GET, or None on 404.
A pass over every profile issues thousands of requests, so a dropped
@@ -355,15 +355,15 @@ def _fetch(url: str, accept_json: bool = False) -> bytes | None:
_sleep(RETRY_BACKOFF[attempt - 1])
def _http_text(url: str) -> str | None:
def http_text(url: str) -> str | None:
"""Text body of a GET, or None on 404. Replaced in tests."""
body = _fetch(url)
body = fetch_body(url)
return None if body is None else body.decode("utf-8", errors="replace")
def _http_json(url: str) -> object | None:
def http_json(url: str) -> object | None:
"""Parsed JSON body of a GET, or None on 404. Replaced in tests."""
body = _fetch(url, accept_json=True)
body = fetch_body(url, accept_json=True)
return None if body is None else json.loads(body.decode())
@@ -419,7 +419,7 @@ def fetch_file(
return None if text == ABSENT else text.splitlines()
if offline:
raise NotCachedError(f"{repo.slug}@{sha[:8]}:{path} is not in the offline cache")
fetched = _http_text(content_url(repo, sha, path))
fetched = http_text(content_url(repo, sha, path))
write_cache(target, ABSENT if fetched is None else fetched)
return None if fetched is None else fetched.splitlines()
@@ -441,14 +441,14 @@ def _api_target(url: str, cache_dir: str) -> Path:
def _require_cached(url: str, cache_dir: str, offline: bool, what: str) -> None:
"""Offline, refuse a call the cache holds no answer to, absence included.
_api answers None both for a resource the forge does not have and for
cached_api answers None both for a resource the forge does not have and for
one never asked, and only the first is a fact.
"""
if offline and not _api_target(url, cache_dir).is_file():
raise NotCachedError(f"{what} is not in the offline cache")
def _api(
def cached_api(
url: str, cache_dir: str, offline: bool, max_age: float | None = None,
absent_max_age: float | None = None,
) -> object | None:
@@ -472,7 +472,7 @@ def _api(
return None if raw == ABSENT else json.loads(raw)
if offline:
return None
payload = _http_json(url)
payload = http_json(url)
write_cache(target, ABSENT if payload is None else json.dumps(payload))
return payload
@@ -492,12 +492,12 @@ def fetch_page(url: str, cache_dir: str, offline: bool) -> str | None:
return None if raw == ABSENT else raw
if offline:
return None
text = _http_text(url)
text = http_text(url)
write_cache(target, ABSENT if text is None else text)
return text
def _project(repo: Repo) -> str:
def project_path(repo: Repo) -> str:
return urllib.parse.quote(f"{repo.owner}/{repo.name}", safe="")
@@ -508,7 +508,7 @@ def _commits_url(repo: Repo, date: str | None, branch: str | None = None) -> str
base += f"&sha={urllib.parse.quote(branch, safe='')}"
elif repo.family == "gitlab":
base = (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/commits?per_page=1"
)
if branch:
@@ -537,10 +537,10 @@ def current_slug(repo: Repo, cache_dir: str, offline: bool = False) -> str | Non
name in the payload tells the project moved.
"""
if repo.family == "gitlab":
url, key = f"{repo.api_base}/projects/{_project(repo)}", "path_with_namespace"
url, key = f"{repo.api_base}/projects/{project_path(repo)}", "path_with_namespace"
else:
url, key = f"{repo.api_base}/repos/{repo.slug}", "full_name"
payload = _api(url, cache_dir, offline, MOVING_TTL)
payload = cached_api(url, cache_dir, offline, MOVING_TTL)
if not isinstance(payload, dict):
return None
value = payload.get(key)
@@ -566,7 +566,7 @@ def resolve_head(
_require_cached(
url, cache_dir, offline, f"{repo.slug}: tip of {branch or 'the default branch'}"
)
return _first_sha(_api(url, cache_dir, offline, 0 if fresh else MOVING_TTL))
return _first_sha(cached_api(url, cache_dir, offline, 0 if fresh else MOVING_TTL))
def resolve_commit_at(
@@ -581,7 +581,7 @@ def resolve_commit_at(
if repo.family in ("github", "gitlab"):
url = _commits_url(repo, date, branch)
_require_cached(url, cache_dir, offline, f"{repo.slug}: commit at {date}")
return _first_sha(_api(url, cache_dir, offline))
return _first_sha(cached_api(url, cache_dir, offline))
return _gitea_commit_at(repo, date, cache_dir, offline, branch)
@@ -610,7 +610,7 @@ def _gitea_commit_at(
while True:
url = f"{base}&page={page}"
_require_cached(url, cache_dir, offline, f"{repo.slug}: commit at {date}")
payload = _api(url, cache_dir, offline, MOVING_TTL)
payload = cached_api(url, cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list) or not payload:
return None
for entry in payload:
@@ -637,7 +637,7 @@ def _gitea_commit_date(entry: object) -> datetime | None:
def _tags_url(repo: Repo) -> str:
if repo.family == "gitlab":
return (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/tags?per_page=100"
)
return f"{repo.api_base}/repos/{repo.slug}/tags?per_page=100"
@@ -645,7 +645,7 @@ def _tags_url(repo: Repo) -> str:
def list_tags(repo: Repo, cache_dir: str, offline: bool = False) -> list[str]:
"""Tag names, newest first as the forge orders them."""
payload = _api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
payload = cached_api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list):
return []
return [t["name"] for t in payload if isinstance(t, dict) and t.get("name")]
@@ -728,7 +728,7 @@ def resolve_tag_commit(
repo: Repo, tag: str, cache_dir: str, offline: bool = False
) -> str | None:
"""Commit a tag points at."""
payload = _api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
payload = cached_api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list):
return None
for entry in payload:
@@ -746,10 +746,10 @@ def _named_tag_commit(
"""A GitLab or Forgejo tag's commit, asked for by name."""
quoted = urllib.parse.quote(tag, safe="")
if repo.family == "gitlab":
url = f"{repo.api_base}/projects/{_project(repo)}/repository/tags/{quoted}"
url = f"{repo.api_base}/projects/{project_path(repo)}/repository/tags/{quoted}"
else:
url = f"{repo.api_base}/repos/{repo.slug}/tags/{quoted}"
payload = _api(url, cache_dir, offline, absent_max_age=MOVING_TTL)
payload = cached_api(url, cache_dir, offline, absent_max_age=MOVING_TTL)
commit = payload.get("commit") if isinstance(payload, dict) else None
if not isinstance(commit, dict):
return None
@@ -772,7 +772,7 @@ def tag_commit(
quoted = urllib.parse.quote(tag)
# A tag pushed after the first lookup must be seen: the 404 expires,
# the commit a tag names does not.
payload = _api(
payload = cached_api(
f"{repo.api_base}/repos/{repo.slug}/git/ref/tags/{quoted}",
cache_dir,
offline,
@@ -785,7 +785,7 @@ def tag_commit(
return None
if obj.get("type") != "tag":
return obj.get("sha")
annotated = _api(
annotated = cached_api(
f"{repo.api_base}/repos/{repo.slug}/git/tags/{obj.get('sha')}",
cache_dir,
offline,
@@ -796,7 +796,7 @@ def tag_commit(
def _releases_url(repo: Repo) -> str:
if repo.family == "gitlab":
return f"{repo.api_base}/projects/{_project(repo)}/releases"
return f"{repo.api_base}/projects/{project_path(repo)}/releases"
return f"{repo.api_base}/repos/{repo.slug}/releases/latest"
@@ -804,7 +804,7 @@ def latest_release(
repo: Repo, cache_dir: str, offline: bool = False
) -> Release | None:
"""Most recent release the forge exposes."""
payload = _api(_releases_url(repo), cache_dir, offline, MOVING_TTL)
payload = cached_api(_releases_url(repo), cache_dir, offline, MOVING_TTL)
if isinstance(payload, list):
payload = payload[0] if payload else None
if not isinstance(payload, dict):
@@ -819,7 +819,7 @@ def latest_release(
def _compare_url(repo: Repo, base: str, head: str) -> str:
if repo.family == "gitlab":
return (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/compare?from={base}&to={head}"
)
return f"{repo.api_base}/repos/{repo.slug}/compare/{base}...{head}"
@@ -859,7 +859,7 @@ def compare(
repo: Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> CompareResult:
"""Tree difference between two revisions."""
payload = _api(_compare_url(repo, base, head), cache_dir, offline)
payload = cached_api(_compare_url(repo, base, head), cache_dir, offline)
if not isinstance(payload, dict):
return CompareResult([], True)
if repo.family == "gitlab":
@@ -894,7 +894,7 @@ def fork_base(
"""
if repo.family != "github" or fork.family != "github":
return None
payload = _api(
payload = cached_api(
f"{repo.api_base}/repos/{repo.slug}/compare/"
f"{sha}...{fork.owner}:{fork.name}:{fork_sha}",
cache_dir, offline,
@@ -912,7 +912,7 @@ def ancestry(
good. GitHub gives both counts in one answer, GitLab and Forgejo list
one direction only and are asked twice.
"""
forward = _api(_compare_url(repo, base, head), cache_dir, offline)
forward = cached_api(_compare_url(repo, base, head), cache_dir, offline)
ahead = _commits_ahead(forward, repo.family)
if ahead is None:
return None
@@ -920,7 +920,7 @@ def ancestry(
behind = forward.get("behind_by") if isinstance(forward, dict) else None
else:
behind = _commits_ahead(
_api(_compare_url(repo, head, base), cache_dir, offline), repo.family
cached_api(_compare_url(repo, head, base), cache_dir, offline), repo.family
)
return (ahead, behind) if isinstance(behind, int) else None
@@ -951,7 +951,7 @@ def list_directory(
if repo.family != "github":
return None
url = f"{repo.api_base}/repos/{repo.slug}/git/trees/{sha}:{path.strip('/')}"
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, dict) or payload.get("truncated"):
return None
return sorted(
@@ -976,10 +976,10 @@ def _gitlab_tree(
paths: list[str] = []
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{_project(repo)}/repository/tree"
f"{repo.api_base}/projects/{project_path(repo)}/repository/tree"
f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
return paths, True
paths.extend(
@@ -1028,10 +1028,10 @@ def cache_gitlab_directory(
def _gitlab_archive_files(repo: Repo, sha: str, directory: str) -> dict[str, str]:
url = (
f"{repo.api_base}/projects/{_project(repo)}/repository/archive.tar.gz"
f"{repo.api_base}/projects/{project_path(repo)}/repository/archive.tar.gz"
f"?sha={sha}&path={urllib.parse.quote(directory)}"
)
body = _fetch(url)
body = fetch_body(url)
if body is None:
return {}
prefix = directory + "/"
@@ -1084,7 +1084,7 @@ def list_tree(
url = _tree_url(repo, sha)
if url is None:
return [], True
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, dict):
return [], True
entries = list(payload.get("tree") or [])
@@ -1098,7 +1098,7 @@ def list_tree(
for page in range(2, MAX_TREE_PAGES + 1):
if len(entries) >= total:
break
more = _api(f"{url}&page={page}", cache_dir, offline)
more = cached_api(f"{url}&page={page}", cache_dir, offline)
if not isinstance(more, dict) or not more.get("tree"):
break
entries.extend(more["tree"])
@@ -1123,10 +1123,10 @@ def list_gitlinks(
links: dict[str, str] = {}
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{_project(repo)}/repository/tree"
f"{repo.api_base}/projects/{project_path(repo)}/repository/tree"
f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
break
links.update(
@@ -1139,7 +1139,7 @@ def list_gitlinks(
break
return links
tree_url = _tree_url(repo, sha)
payload = _api(tree_url, cache_dir, offline) if tree_url else None
payload = cached_api(tree_url, cache_dir, offline) if tree_url else None
if not isinstance(payload, dict):
return {}
return {
@@ -1205,8 +1205,8 @@ def through_gitlink(
def commit_date(repo: Repo, sha: str, cache_dir: str, offline: bool = False) -> str | None:
"""When a revision was committed, as the forge reports it (ISO 8601)."""
if repo.family == "gitlab":
payload = _api(
f"{repo.api_base}/projects/{_project(repo)}/repository/commits/{sha}",
payload = cached_api(
f"{repo.api_base}/projects/{project_path(repo)}/repository/commits/{sha}",
cache_dir, offline,
)
value = payload.get("committed_date") if isinstance(payload, dict) else None
@@ -1215,7 +1215,7 @@ def commit_date(repo: Repo, sha: str, cache_dir: str, offline: bool = False) ->
url = f"{repo.api_base}/repos/{repo.slug}/commits/{sha}"
else:
url = f"{repo.api_base}/repos/{repo.slug}/git/commits/{sha}"
stamp = _gitea_commit_date(_api(url, cache_dir, offline))
stamp = _gitea_commit_date(cached_api(url, cache_dir, offline))
return stamp.isoformat() if stamp is not None else None
@@ -1238,7 +1238,7 @@ def commits_touching(
stamp = urllib.parse.quote(since)
if repo.family == "gitlab":
url = (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/commits?path={quoted}&since={stamp}&per_page=100"
)
elif repo.family == "github":
@@ -1253,7 +1253,7 @@ def commits_touching(
)
# The list grows with every push touching the path: cached for good, the
# triage drift score stayed at whatever the first run counted.
payload = _api(url, cache_dir, offline, MOVING_TTL)
payload = cached_api(url, cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list):
return 0
return sum(
+2 -2
View File
@@ -35,7 +35,7 @@ from resolve.launchers import (
from packs.crossref import (
DEFAULT_PLATFORMS_DIR,
_build_supplemental_index,
build_supplemental_index,
cross_reference,
declared_names,
folded_declared_slots,
@@ -367,7 +367,7 @@ def main() -> None:
selected = [args.platform] if args.platform else None
declared, plat_data_dirs = load_platform_files(args.platforms_dir, selected)
db = load_database(args.db)
data_names = _build_supplemental_index()
data_names = build_supplemental_index()
report = cross_reference(
profiles, declared, db, plat_data_dirs, data_names,
all_declared=declared_names(args.platforms_dir, selected, db),
+2 -2
View File
@@ -31,7 +31,7 @@ sys.path.insert(0, os.path.dirname(__file__))
from core.hashing import compute_hashes
from core.cli import require_directory
from core.artifacts import write_text_atomic
from model.nodedup import _in_nodedup_dir
from model.nodedup import in_nodedup_dir
DEFAULT_BIOS_DIR = "bios"
@@ -66,7 +66,7 @@ def scan_duplicates(bios_dir: str) -> dict[str, list[str]]:
for root, _dirs, files in os.walk(bios_dir):
for name in files:
path = os.path.join(root, name)
if _in_nodedup_dir(path):
if in_nodedup_dir(path):
continue
by_size[os.path.getsize(path)].append(path)
+1 -4
View File
@@ -11,9 +11,6 @@ from dataclasses import dataclass, field
from core.paths import REPO_ROOT
ROOT = REPO_ROOT
@dataclass(frozen=True)
class Step:
command: str
@@ -72,7 +69,7 @@ def shown(step: Step) -> str:
def execute(step: Step) -> int:
env = {**os.environ, **step.env}
return subprocess.run(argv(step.command), cwd=ROOT, env=env, check=False).returncode
return subprocess.run(argv(step.command), cwd=REPO_ROOT, env=env, check=False).returncode
def run(steps: tuple[Step, ...] = STEPS) -> int:
+5 -5
View File
@@ -18,8 +18,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from resolve.archives import contents_members, holds_required_members
from resolve.standalone import platform_layouts, standalone_set
from resolve.cores import resolve_platform_cores
from resolve.reconcile import HASH_FIELDS, _hash_values
from resolve.collisions import _accepted_by_all, _lists_hashes, find_collisions
from resolve.reconcile import HASH_FIELDS, hash_values
from resolve.collisions import accepted_by_all, lists_hashes, find_collisions
from resolve.validation import opens_by_name, outside_gap_scope
@@ -58,13 +58,13 @@ def _reads(entry: dict, by_name: bool, local: str, db: dict) -> bool:
"""
if entry.get("contents"):
return holds_required_members(local, contents_members(entry))
if _lists_hashes(entry):
return _accepted_by_all(local, [entry], db)
if lists_hashes(entry):
return accepted_by_all(local, [entry], db)
return by_name and _size_fits(entry, local)
def _hashes(entry: dict) -> dict[str, list[str]]:
found = {f: _hash_values(entry, f) for f in HASH_FIELDS}
found = {f: hash_values(entry, f) for f in HASH_FIELDS}
return {f: values for f, values in found.items() if values}
+7 -7
View File
@@ -15,10 +15,10 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from scraper.emudeck_scraper import FUNCTION_HASH_MAP, _RE_FUNC, _RE_LOCAL_HASHES
from scraper.emudeck_scraper import FUNCTION_HASH_MAP, RE_FUNC, RE_LOCAL_HASHES
from .base_exporter import BaseExporter
from resolve.reconcile import NativeFile, NativeSystem, Report, _hash_values
from resolve.reconcile import NativeFile, NativeSystem, Report, hash_values
SOURCE_URL = (
"https://raw.githubusercontent.com/dragoonDorise/EmuDeck/main"
@@ -80,7 +80,7 @@ class Exporter(BaseExporter[str]):
adds nothing, and the truth's extra accepted revisions are not
appended: either would grow an array other consumers read too.
"""
theirs = _hash_values(fe.platform or {}, "md5")
theirs = hash_values(fe.platform or {}, "md5")
if not theirs:
return []
if "md5" in fe.corrections:
@@ -124,7 +124,7 @@ class Exporter(BaseExporter[str]):
if system.native_id == system_id
for fe in system.files
if "md5" in fe.corrections
for value in _hash_values(fe.platform or {}, "md5")
for value in hash_values(fe.platform or {}, "md5")
}
@classmethod
@@ -146,7 +146,7 @@ class Exporter(BaseExporter[str]):
def _function_spans(self, script: str) -> list[tuple[str, int, int]]:
"""Name and byte span of every check the script defines."""
matches = list(_RE_FUNC.finditer(script))
matches = list(RE_FUNC.finditer(script))
spans: list[tuple[str, int, int]] = []
for index, match in enumerate(matches):
end = (
@@ -179,7 +179,7 @@ class Exporter(BaseExporter[str]):
body = script[start:end]
system_id = FUNCTION_HASH_MAP.get(name)
md5s = self._md5s(systems, system_id) if system_id else []
match = _RE_LOCAL_HASHES.search(body)
match = RE_LOCAL_HASHES.search(body)
if md5s and match:
# An array compared by membership says nothing about order,
# so the same set is left as the maintainer wrote it.
@@ -226,7 +226,7 @@ class Exporter(BaseExporter[str]):
for fname, start, end in self._function_spans(content)
if fname == name
)
if not _RE_LOCAL_HASHES.search(body):
if not RE_LOCAL_HASHES.search(body):
# A check with no hash list is a path check, not a hash check.
continue
issues.extend(f"absent from {name}: {md5}" for md5 in md5s if md5 not in body)
+8 -8
View File
@@ -6,7 +6,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from .base_exporter import BaseExporter
from resolve.reconcile import HASH_FIELDS, NativeFile, _hash_values, _single_size
from resolve.reconcile import HASH_FIELDS, NativeFile, hash_values, single_size
@dataclass
@@ -75,7 +75,7 @@ def _change(
def _platform_value(entry: NativeFile, field_name: str) -> str | list[str]:
values = _hash_values(entry.platform or {}, field_name)
values = hash_values(entry.platform or {}, field_name)
if (entry.platform or {}).get(f"{field_name}_list"):
return values
return ",".join(values)
@@ -157,7 +157,7 @@ def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges:
listed is not None
and field_name not in entry.corrections
and field_name not in entry.filled
and listed != _hash_values(entry.platform, field_name)
and listed != hash_values(entry.platform, field_name)
and exporter.states(entry, field_name)
):
records.append(_change(
@@ -175,28 +175,28 @@ def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges:
if (
theirs
and ours
and _single_size(theirs) not in (None, ours)
and single_size(theirs) not in (None, ours)
and exporter.states(entry, "size")
):
records.append(_change(
"size_updated", entry, "size", _single_size(theirs), ours
"size_updated", entry, "size", single_size(theirs), ours
))
elif (
theirs
and ours is None
and _single_size(theirs) is not None
and single_size(theirs) is not None
and exporter.states(entry, "size")
):
# The truth took the entry over without a size of its own:
# System.dat's neocdz.zip line went out without size 953078.
records.append(_change(
"size_removed", entry, "size", _single_size(theirs), None
"size_removed", entry, "size", single_size(theirs), None
))
records.extend(
_change("hash_cleared", entry, field_name,
_platform_value(entry, field_name), None)
for field_name in HASH_FIELDS
if _hash_values(entry.platform, field_name)
if hash_values(entry.platform, field_name)
and not entry.hashes(field_name)
and exporter.clears(entry, field_name)
)
+3 -3
View File
@@ -18,7 +18,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from scraper.romm_scraper import SLUG_MAP
from .base_exporter import BaseExporter
from resolve.reconcile import NativeFile, NativeSystem, Report, _hash_values
from resolve.reconcile import NativeFile, NativeSystem, Report, hash_values
SOURCE_URL = (
"https://raw.githubusercontent.com/rommapp/romm/master/backend/models"
@@ -161,7 +161,7 @@ class Exporter(BaseExporter[str]):
output[key] = OrderedDict(
(field, value)
for field, name in _FIELDS
if (value := ",".join(_hash_values(fe.platform, name))
if (value := ",".join(hash_values(fe.platform, name))
if name != "size" else str(fe.platform["size"]))
)
continue
@@ -185,7 +185,7 @@ class Exporter(BaseExporter[str]):
def _contradicted(fe: NativeFile, name: str) -> bool:
"""A hash the platform states and the truth, taking the entry over,
does not keep."""
return bool(_hash_values(fe.platform or {}, name)) and not fe.hashes(name)
return bool(hash_values(fe.platform or {}, name)) and not fe.hashes(name)
def states(self, fe: NativeFile, field_name: str) -> bool:
"""An entry left whole carries none of the truth's values."""
+4 -4
View File
@@ -198,13 +198,13 @@ def fetch_logos() -> None:
def fetch_icons() -> None:
from model.database import load_database
from model.collection import _group_by_manufacturer
from sitegen.render import SYSTEM_ICON_BASE, _icon_name
from model.collection import group_by_manufacturer
from sitegen.render import SYSTEM_ICON_BASE, console_icon_name
db = load_database(str(ROOT / "database.json"))
names = sorted({
_icon_name(manufacturer, console)
for manufacturer, consoles in _group_by_manufacturer(db).items()
console_icon_name(manufacturer, console)
for manufacturer, consoles in group_by_manufacturer(db).items()
for console in consoles
})
ICON_DIR.mkdir(parents=True, exist_ok=True)
+23 -23
View File
@@ -85,22 +85,22 @@ from resolve.packfiles import (
from packs.archive import DamagedArchiveError
from packs.platformpack import generate_split_packs
from packs.datatrees import _MISSING_DATA_DIRS
from packs.datatrees import MISSING_DATA_DIRS
from packs.emulatorpack import generate_emulator_pack, generate_system_pack
from packs.finalize import _baseline_shortfall, verify_and_finalize_packs
from packs.finalize import baseline_shortfall, verify_and_finalize_packs
from packs.manifest import generate_install_list, generate_manifest
from packs.md5pack import generate_md5_pack
from packs.naming import (
_expected_pack_names,
_narrowings,
_pack_variant,
_platform_pack_stem,
_platform_target,
_system_tag,
expected_pack_names,
pack_narrowings,
pack_variant,
platform_pack_stem,
platform_target,
system_tag,
)
from packs.platformpack import generate_pack
from packs.scope import pack_systems, platform_list_version
from packs.standalone import STANDALONE_DIR, _standalone_copies
from packs.standalone import STANDALONE_DIR, standalone_copies
from packs.targets import generate_target_manifests, target_list
@@ -382,7 +382,7 @@ def _run_manifest_mode(
target_cores=tc,
source=source,
regions=getattr(args, "regions", None),
target_name=_platform_target(
target_name=platform_target(
representative, args.target, args.platforms_dir
),
offline=args.offline,
@@ -392,10 +392,10 @@ def _run_manifest_mode(
)
narrow_suffix = "".join(
tag.lower()
for tag, _label in _narrowings(
for tag, _label in pack_narrowings(
source,
getattr(args, "regions", None),
_platform_target(representative, args.target, args.platforms_dir),
platform_target(representative, args.target, args.platforms_dir),
False,
required_only,
no_game_data=getattr(args, "no_game_data", False),
@@ -438,7 +438,7 @@ def _run_manifest_mode(
alias_manifest["detect"] = alias_install.get("detect", [])
# Placed and completed as the representative's are:
# copied raw, an alias's copies named no source.
alias_manifest["standalone_copies"] = _standalone_copies(
alias_manifest["standalone_copies"] = standalone_copies(
alias_install.get("standalone_copies", []),
{name: emu_profiles[name]
for name in _platform_cores(alias_cfg, emu_profiles)},
@@ -528,7 +528,7 @@ def _run_verify_packs(args: argparse.Namespace) -> None:
)
# After an --all-variants build every variant is named, so none of the
# six packs the run wrote passes unmentioned.
expected = _expected_pack_names(
expected = expected_pack_names(
platforms,
args.platforms_dir,
check.regions,
@@ -564,7 +564,7 @@ def _run_verify_packs(args: argparse.Namespace) -> None:
# A group pack and a pack built for the platform alone can both be
# present, and each one is a pack of this platform.
for pack_name in found:
variant = _pack_variant(pack_name)
variant = pack_variant(pack_name)
if variant is None:
# One BIOS per slot: the slot choice is not replayed here.
print(
@@ -593,7 +593,7 @@ def _run_verify_packs(args: argparse.Namespace) -> None:
# These explain a baseline short of its total: a dump whose hash
# the frontend refuses is left out on purpose, and a file the
# collection does not hold cannot be packed (verify reports it).
shortfall = ", ".join(_baseline_shortfall(bl_excluded, bl_absent))
shortfall = ", ".join(baseline_shortfall(bl_excluded, bl_absent))
excluded = f" ({shortfall})" if shortfall else ""
counts = (
f"{bl_present}/{bl_checked} baseline{excluded}, "
@@ -722,7 +722,7 @@ def _run_platform_packs(
zip_path = None
zip_paths: list = []
tc = target_cores_cache.get(representative) if args.target else None
named_target = _platform_target(representative, args.target, args.platforms_dir)
named_target = platform_target(representative, args.target, args.platforms_dir)
if _skip_empty_truth(args, source, representative, emu_profiles, tc, failed):
continue
try:
@@ -834,7 +834,7 @@ def _group_pack_name(
source, required_only = variant
narrow_tags = "".join(
tag
for tag, _label in _narrowings(
for tag, _label in pack_narrowings(
source,
getattr(args, "regions", None),
named_target,
@@ -843,12 +843,12 @@ def _group_pack_name(
no_game_data=getattr(args, "no_game_data", False),
)
)
stem = _platform_pack_stem(
stem = platform_pack_stem(
group_platforms, representative, args.platforms_dir
)
return (
f"{stem}{narrow_tags}_BIOS_Pack"
f"{_system_tag(system_filter)}.zip"
f"{system_tag(system_filter)}.zip"
)
@@ -1033,7 +1033,7 @@ def _given_flags(args: argparse.Namespace) -> set[str]:
def main() -> None:
# One run's account: tests call main() repeatedly in one process, and a
# notice left by an earlier run failed a later one that missed nothing.
_MISSING_DATA_DIRS.clear()
MISSING_DATA_DIRS.clear()
with contextlib.ExitStack() as held:
try:
_main(held)
@@ -1042,10 +1042,10 @@ def main() -> None:
# report it: the run stops with the file to restore.
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)
if _MISSING_DATA_DIRS:
if MISSING_DATA_DIRS:
print(
"ERROR: packs written without data directories that are not cached: "
f"{', '.join(sorted(_MISSING_DATA_DIRS))} (run refresh_data_dirs.py)",
f"{', '.join(sorted(MISSING_DATA_DIRS))} (run refresh_data_dirs.py)",
file=sys.stderr,
)
sys.exit(1)
+2 -2
View File
@@ -17,7 +17,7 @@ import sys
sys.path.insert(0, os.path.dirname(__file__))
from model.database import load_database
from core.artifacts import repository_output_lock
from sitegen.readme import _write, generate_readme
from sitegen.readme import write_readme, generate_readme
def main() -> None:
@@ -44,7 +44,7 @@ def main() -> None:
with repository_output_lock("README.md"), contextlib.ExitStack() as held:
hold_data_dirs(held, load_data_dir_registry(args.platforms_dir))
readme = generate_readme(db, args.platforms_dir, args.db)
_write(readme)
write_readme(readme)
if __name__ == "__main__":
+2 -2
View File
@@ -23,7 +23,7 @@ sys.path.insert(0, os.path.dirname(__file__))
from core.cli import require_directory
from core.artifacts import ArtifactLockBusy, artifact_lock
from sitegen.build import _generate
from sitegen.build import generate_site
from sitegen.config import STARLIGHT_CONTENT, STARLIGHT_DIR
from sitegen.parts import PUBLISHED_PARTS_FILE
@@ -79,7 +79,7 @@ def main() -> None:
repository_output_lock(str(PUBLISHED_PARTS_FILE)), \
contextlib.ExitStack() as held:
hold_data_dirs(held, load_data_dir_registry(args.platforms_dir))
_generate(args)
generate_site(args)
except ArtifactLockBusy as exc:
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)
-2
View File
@@ -9,10 +9,8 @@ from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
from core.paths import REPO_ROOT
ROOT = REPO_ROOT
PACKAGE = "installer"
OUTPUT = "install.py"
COMMAND = "python scripts/build_installer.py"
+3 -4
View File
@@ -8,12 +8,11 @@ import json
from core.paths import REPO_ROOT
ROOT = REPO_ROOT
OUTPUT = ROOT / "schemas" / "install-events.schema.json"
OUTPUT = REPO_ROOT / "schemas" / "install-events.schema.json"
_spec = importlib.util.spec_from_file_location("install", ROOT / "install.py")
_spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py")
if _spec is None or _spec.loader is None:
raise ImportError(f"cannot load {ROOT / 'install.py'}")
raise ImportError(f"cannot load {REPO_ROOT / 'install.py'}")
_install = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_install)
+9 -10
View File
@@ -28,9 +28,8 @@ if TYPE_CHECKING:
from install import LocalCopy, Progress, _OsRule
ROOT = REPO_ROOT
PAGE = ROOT / "wiki" / "installer.md"
INSTALLER = ROOT / "install.py"
PAGE = REPO_ROOT / "wiki" / "installer.md"
INSTALLER = REPO_ROOT / "install.py"
_spec = importlib.util.spec_from_file_location("install", INSTALLER)
if _spec is None or _spec.loader is None:
@@ -216,7 +215,7 @@ def line_menu() -> str:
import io
from unittest import mock
manifest = json.loads((ROOT / "install" / "retroarch.json").read_text(encoding="utf-8"))
manifest = json.loads((REPO_ROOT / "install" / "retroarch.json").read_text(encoding="utf-8"))
files = [*manifest["files"], *(manifest.get("case_variants") or [])]
folder = Path(MENU_FOLDER)
out = io.StringIO()
@@ -266,7 +265,7 @@ class _ListHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, request: socket.socket | tuple[bytes, socket.socket],
client_address: tuple[str, int], server: socketserver.BaseServer) -> None:
super().__init__(request, client_address, server, directory=str(ROOT))
super().__init__(request, client_address, server, directory=str(REPO_ROOT))
def do_GET(self) -> None:
if not re.fullmatch(r"/install/[a-z0-9_-]+\.json", self.path):
@@ -398,8 +397,8 @@ class Sandbox:
is printed here."""
def __enter__(self) -> Sandbox:
(ROOT / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(prefix="installer-doc-", dir=ROOT / "tmp"))
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(prefix="installer-doc-", dir=REPO_ROOT / "tmp"))
self.home = self.root / "home"
self.card = self.root / "card"
config = self.home / ".config" / "retroarch" / "retroarch.cfg"
@@ -458,7 +457,7 @@ class Sandbox:
"RETROBIOS_BASE_URL": f"http://127.0.0.1:{self.server.server_address[1]}"}
done = subprocess.run(
[sys.executable, "-s", "-c", CHILD, json.dumps(spec)],
cwd=ROOT, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True,
cwd=REPO_ROOT, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True,
check=False)
if done.returncode not in codes:
raise SampleFailed(f"install.py {' '.join(args)} exited "
@@ -473,7 +472,7 @@ _RUNS: dict[tuple, str] = {}
def _stamp(platform: str) -> tuple[int, int]:
return (hash(INSTALLER.read_bytes()),
hash((ROOT / "install" / f"{platform}.json").read_bytes()))
hash((REPO_ROOT / "install" / f"{platform}.json").read_bytes()))
class _LazySandbox:
@@ -529,7 +528,7 @@ def _fenced(lines: list[str]) -> str:
def list_date(platform: str) -> str:
"""The day the committed list was generated, which dates its samples."""
manifest = json.loads((ROOT / "install" / f"{platform}.json").read_text(encoding="utf-8"))
manifest = json.loads((REPO_ROOT / "install" / f"{platform}.json").read_text(encoding="utf-8"))
return manifest["generated"][:10]
+2 -2
View File
@@ -13,7 +13,7 @@ from installer_build.port import (
BATOCERA_ZIP,
MUOS_APP,
TOOLS_ZIP,
_packs_table,
packs_table,
archive_members,
pinned_installer_sha256,
)
@@ -35,7 +35,7 @@ def _entry(field: str, name: str, source: Path | None, root: Path) -> dict:
"""A member as the list records it: where it comes from, its size and
hash, and whether it is executable in the repository."""
if source is None:
data = _packs_table(root)
data = packs_table(root)
origin: dict = {"content": data.decode("utf-8")}
executable = False
else:
+3 -4
View File
@@ -10,7 +10,6 @@ from core.paths import REPO_ROOT
from model.guides import PS1_NAME, SH_NAME
ROOT = REPO_ROOT
INSTALLER = "install.py"
# Each bootstrap and its one pin line, the value between the two groups.
PINS: dict[str, re.Pattern[str]] = {
@@ -25,11 +24,11 @@ PIN: dict[str, re.Pattern[str]] = {
COMMAND = "python scripts/pin_installer.py"
def installer_sha256(root: Path = ROOT) -> str:
def installer_sha256(root: Path = REPO_ROOT) -> str:
return hashlib.sha256((root / INSTALLER).read_bytes()).hexdigest()
def stale_pins(root: Path = ROOT) -> list[str]:
def stale_pins(root: Path = REPO_ROOT) -> list[str]:
"""The bootstraps whose pin is not the SHA-256 of install.py."""
digest = installer_sha256(root)
stale = []
@@ -42,7 +41,7 @@ def stale_pins(root: Path = ROOT) -> list[str]:
return stale
def write_pins(root: Path = ROOT) -> list[str]:
def write_pins(root: Path = REPO_ROOT) -> list[str]:
"""Rewrite each stale pin. Returns the bootstraps written."""
digest = installer_sha256(root)
written = []
+7 -7
View File
@@ -112,23 +112,23 @@ def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]:
from resolve.grouping import group_identical_platforms
from model.registry import list_release_pack_platforms
from model.platforms import load_platform_config
from packs.naming import _name_part, _platform_pack_stem
from packs.naming import file_name_part, platform_pack_stem
platforms_dir = str(root / "platforms")
pool = list_release_pack_platforms(platforms_dir)
labels: dict[str, str] = {}
for group, representative in group_identical_platforms(pool, platforms_dir):
stem = _platform_pack_stem(group, representative, platforms_dir)
stem = platform_pack_stem(group, representative, platforms_dir)
config = load_platform_config(representative, platforms_dir)
version = config.get("version", config.get("dat_version", ""))
tag = f"_{_name_part(str(version))}" if version else ""
tag = f"_{file_name_part(str(version))}" if version else ""
label = stem[: -len(tag)] if tag and stem.endswith(tag) else stem
for platform in group:
labels[platform] = label
return dict(sorted(labels.items()))
def _packs_table(root: Path) -> bytes:
def packs_table(root: Path) -> bytes:
return "".join(f"{platform}\t{label}\n"
for platform, label in release_pack_labels(root).items()).encode()
@@ -144,17 +144,17 @@ def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path:
)
# The packs' member writer: imported here, as it loads the whole
# pack builder, which a caller reading ARCHIVES does not need.
from packs.archive import _add_pack_member
from packs.archive import add_pack_member
members = archive_members(name, root)
output.parent.mkdir(parents=True, exist_ok=True)
scratch = output.with_name(f".{output.name}.tmp")
table = output.with_name(f".{output.name}.{PACKS_TABLE}")
table.write_bytes(_packs_table(root))
table.write_bytes(packs_table(root))
try:
with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
for member, path in members:
_add_pack_member(zf, str(path or table), member)
add_pack_member(zf, str(path or table), member)
finally:
table.unlink()
scratch.replace(output)
+7 -8
View File
@@ -15,9 +15,8 @@ from model.guides import SH_NAME
from installer_build.pins import PIN
ROOT = REPO_ROOT
PACKAGE_DIR = ROOT / "packaging" / "pypi"
DEFAULT_OUTPUT = ROOT / "tmp" / "pypi-dist"
PACKAGE_DIR = REPO_ROOT / "packaging" / "pypi"
DEFAULT_OUTPUT = REPO_ROOT / "tmp" / "pypi-dist"
MODULE = "retrobios"
# The launcher. runpy runs install.py as __main__, so its own __main__ block
@@ -51,7 +50,7 @@ def package_version(stamps: list[int]) -> str:
def install_py_commits() -> list[int]:
"""Commit times of install.py, newest first, from git."""
out = subprocess.run(["git", "log", "--format=%ct", "--", "install.py"], cwd=ROOT,
out = subprocess.run(["git", "log", "--format=%ct", "--", "install.py"], cwd=REPO_ROOT,
capture_output=True, text=True, check=True).stdout
return [int(line) for line in out.split()]
@@ -59,8 +58,8 @@ def install_py_commits() -> list[int]:
def installer_bytes() -> bytes:
"""install.py, refused unless it is the one install.sh pins: the package
then runs the installer the one-line command runs, under the same id."""
data = (ROOT / "install.py").read_bytes()
pins = PIN[SH_NAME].findall((ROOT / "install.sh").read_text(encoding="utf-8"))
data = (REPO_ROOT / "install.py").read_bytes()
pins = PIN[SH_NAME].findall((REPO_ROOT / "install.sh").read_text(encoding="utf-8"))
if pins != [hashlib.sha256(data).hexdigest()]:
raise ValueError("install.py is not the installer install.sh pins: recompute the pin")
return data
@@ -72,7 +71,7 @@ def stage(folder: Path, version: str) -> None:
module.mkdir(parents=True)
for name in ("pyproject.toml", "README.md"):
shutil.copyfile(PACKAGE_DIR / name, folder / name)
shutil.copyfile(ROOT / "LICENSE", folder / "LICENSE")
shutil.copyfile(REPO_ROOT / "LICENSE", folder / "LICENSE")
shutil.copyfile(PACKAGE_DIR / MODULE / "__main__.py", module / "__main__.py")
(module / "__init__.py").write_text(LAUNCHER.format(version=version), encoding="utf-8")
(module / "install.py").write_bytes(installer_bytes())
@@ -86,7 +85,7 @@ def build(output_dir: Path) -> tuple[Path, Path]:
for pattern in ("*.whl", "*.tar.gz"):
for old in output_dir.glob(f"{MODULE}-{pattern}"):
old.unlink()
scratch = ROOT / "tmp"
scratch = REPO_ROOT / "tmp"
scratch.mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(prefix="pypi-stage-", dir=scratch) as name:
folder = Path(name) / "retrobios"
+3 -3
View File
@@ -73,7 +73,7 @@ def system_cards() -> dict[str, tuple[str, str]]:
system pages are written from."""
from model.composition import GAME_DATA_TOPS
from model.database import load_database
from model.collection import _group_by_manufacturer, _slug
from model.collection import group_by_manufacturer, manufacturer_slug
def lead(manufacturer: str) -> str:
# Other holds one folder per emulator, a game publisher's page its
@@ -82,9 +82,9 @@ def system_cards() -> dict[str, tuple[str, str]]:
return "Game data for"
return "Files kept for the emulators" if manufacturer == "Other" else "BIOS files for"
manufacturers = _group_by_manufacturer(load_database(str(ROOT / "database.json")))
manufacturers = group_by_manufacturer(load_database(str(ROOT / "database.json")))
return {
f"systems/{_slug(manufacturer)}": (
f"systems/{manufacturer_slug(manufacturer)}": (
manufacturer, consoles_tagline(list(consoles), lead(manufacturer)))
for manufacturer, consoles in sorted(manufacturers.items())
}
+2 -2
View File
@@ -29,7 +29,7 @@ sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from core.cli import require_directory
from model.safeparse import yaml_load
from scraper.mame_parser import _MACHINE_MACROS, strip_comments
from scraper.mame_parser import MACHINE_MACROS, strip_comments
# An optional role word names the repository the lines are in.
DRIVER_REF = re.compile(r"^(?:(source|upstream) )?(src/[\w./+-]+):(\d+)$")
@@ -50,7 +50,7 @@ class Finding:
def declares(line: str, set_name: str) -> bool:
"""Whether this line is the machine declaration of that set."""
clean = strip_comments(line)
match = _MACHINE_MACROS.search(clean)
match = MACHINE_MACROS.search(clean)
if not match:
return False
args = clean[match.end():].split(",")
+13 -13
View File
@@ -16,7 +16,7 @@ from model.composition import GAME_DATA_TOPS
from model.profiles import load_emulator_profiles
def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]:
def copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]:
"""sha1 -> every (manufacturer, console, file name) holding a copy.
The database keeps one path per content, deduplication having left one
@@ -39,7 +39,7 @@ def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]:
return places
def _slug(manufacturer: str) -> str:
def manufacturer_slug(manufacturer: str) -> str:
return manufacturer.lower().replace(" ", "-")
@@ -65,7 +65,7 @@ def collection_paths(db: dict) -> dict[str, set[str]]:
return paths
def _group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]:
def group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]:
"""Group files by manufacturer -> console -> files.
The database keeps one path per content, and a copy filed elsewhere was
@@ -76,7 +76,7 @@ def _group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]:
"""
files = db.get("files", {})
manufacturers: dict[str, dict[str, list]] = {}
for sha1, where in _copy_places(db).items():
for sha1, where in copy_places(db).items():
for manufacturer, console in sorted({(m, c) for m, c, _ in where}):
manufacturers.setdefault(manufacturer, {}).setdefault(console, []).append(files[sha1])
return _engine_sections(manufacturers)
@@ -94,7 +94,7 @@ def _engine_sections(manufacturers: dict[str, dict[str, list]]) -> dict[str, dic
the engine's name (SECTION_LABELS), its address unchanged.
"""
profiles = {key: profile for key, profile in _profiles_on_disk().items()
profiles = {key: profile for key, profile in profiles_on_disk().items()
if profile.get("type") != "alias" and profile.get("role") != "test"}
engines = _Engines(profiles, _file_readers(profiles))
out: dict[str, dict[str, list]] = {}
@@ -168,7 +168,7 @@ def _join_other_folders(out: dict[str, dict[str, list]]) -> None:
for folder in sorted(others):
top = next((t for t in out if t in GAME_DATA_TOPS and t.casefold() == folder.casefold()),
None)
if top is None or top in _PROGRAM_TOPS:
if top is None or top in PROGRAM_TOPS:
continue
sections = out[top]
target = next((c for c in sections if c.casefold() == folder.casefold()), folder)
@@ -179,27 +179,27 @@ def _join_other_folders(out: dict[str, dict[str, list]]) -> None:
*(f for f in others.pop(folder) if str(f.get("sha1", "")) not in held)]
def _profiles_on_disk() -> dict[str, dict]:
return _profiles_in(str(siteinputs.current().emulators), skip_aliases=False)
def profiles_on_disk() -> dict[str, dict]:
return profiles_in(str(siteinputs.current().emulators), skip_aliases=False)
@functools.cache
def _profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]:
def profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]:
return load_emulator_profiles(emulators_dir, skip_aliases=skip_aliases)
# (manufacturer slug, folder, sha1) -> the (manufacturer slug, console) a
# copy's card went to when the system pages file it outside its folder:
# ScummVM's engine data under Other/ScummVM, neogeo.zip under Arcade.
_card_moves: dict[tuple[str, str, str], tuple[str, str]] = {}
card_moves: dict[tuple[str, str, str], tuple[str, str]] = {}
def record_card_move(manufacturer: str, folder: str, sha1: str,
to_manufacturer: str, to_console: str) -> None:
"""Mark that the card of the copy under bios/<manufacturer>/<folder>/
sits in the section (to_manufacturer, to_console)."""
_card_moves[(_slug(manufacturer), folder, str(sha1))] = (
_slug(to_manufacturer), to_console)
card_moves[(manufacturer_slug(manufacturer), folder, str(sha1))] = (
manufacturer_slug(to_manufacturer), to_console)
# System display names. A system is named by the heading of the console
@@ -212,7 +212,7 @@ def record_card_move(manufacturer: str, folder: str, sha1: str,
# Folders that file copies by the emulator or board that loads them. Their
# headings name a program, not a system.
_PROGRAM_TOPS = frozenset({"Other", "Arcade"})
PROGRAM_TOPS = frozenset({"Other", "Arcade"})
# A section whose folder is a short name the code reads, headed with the
+1 -1
View File
@@ -49,6 +49,6 @@ NODEDUP_DIRS = {
}
def _in_nodedup_dir(path: str) -> bool:
def in_nodedup_dir(path: str) -> bool:
parts = Path(path).parts
return any(nodedup in parts for nodedup in NODEDUP_DIRS)
+10 -10
View File
@@ -15,7 +15,7 @@ except ImportError:
from core.cli import InputMissing, suggest_names
from model.alternatives import derive_member_requirements
from model.sources import source_yaml
from model.systems import _norm_system_id
from model.systems import norm_system_id
from core.paths import REPO_ROOT
@@ -24,7 +24,7 @@ from core.paths import REPO_ROOT
CONTENT_CHECKS = frozenset({"romdir", "masked_sha1"})
_emulator_profiles_cache: dict[tuple[str, bool], dict[str, dict]] = {}
emulator_profiles_cache: dict[tuple[str, bool], dict[str, dict]] = {}
class ProfileSelectionError(ValueError):
@@ -40,14 +40,14 @@ def profiles_for_systems(
other profile writes atari-2600, and an exact match built two different
packs under one file name, the second replacing the first.
"""
wanted = {_norm_system_id(sid) for sid in system_ids}
wanted = {norm_system_id(sid) for sid in system_ids}
matching = []
for name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias") or profile.get("role") == "test":
continue
if standalone and "standalone" not in profile.get("type", "libretro"):
continue
if wanted & {_norm_system_id(sid) for sid in profile.get("systems", [])}:
if wanted & {norm_system_id(sid) for sid in profile.get("systems", [])}:
matching.append(name)
return matching
@@ -73,8 +73,8 @@ def entry_serves_systems(entry: dict, profile: dict, system_ids: list[str]) -> b
serves every system of its profile, the rule a platform pack applies to
core extras.
"""
wanted = {_norm_system_id(sid) for sid in system_ids}
return bool(wanted & {_norm_system_id(sid) for sid in entry_system_ids(entry, profile)})
wanted = {norm_system_id(sid) for sid in system_ids}
return bool(wanted & {norm_system_id(sid) for sid in entry_system_ids(entry, profile)})
def select_emulator_profiles(
@@ -187,8 +187,8 @@ def load_emulator_profiles(
) -> dict[str, dict]:
"""Load all emulator YAML profiles from a directory (cached)."""
cache_key = (os.path.realpath(emulators_dir), skip_aliases)
if cache_key in _emulator_profiles_cache:
return _emulator_profiles_cache[cache_key]
if cache_key in emulator_profiles_cache:
return emulator_profiles_cache[cache_key]
if skip_aliases:
# A filter over the full set: parsed once, 534 YAML files cost 1.6 s
# every time a process asked for both variants.
@@ -197,7 +197,7 @@ def load_emulator_profiles(
for name, profile in load_emulator_profiles(emulators_dir, False).items()
if profile.get("type") != "alias"
}
_emulator_profiles_cache[cache_key] = profiles
emulator_profiles_cache[cache_key] = profiles
return profiles
if importlib.util.find_spec("yaml") is None:
# Every consumer reads {} as "this repo documents no emulator", which
@@ -223,7 +223,7 @@ def load_emulator_profiles(
_normalize_hash_fields(profile)
derive_member_requirements(profile)
profiles[f.stem] = profile
_emulator_profiles_cache[cache_key] = profiles
emulator_profiles_cache[cache_key] = profiles
return profiles
+4 -4
View File
@@ -57,11 +57,11 @@ AREA_TERRITORIES: dict[str, frozenset[str]] = {
"asia-pal": frozenset({"china"}),
}
_PARENT: dict[str, str] = {
PARENT: dict[str, str] = {
member: parent for parent, members in REGION_TREE.items() for member in members
}
REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(_PARENT))
REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(PARENT))
# Accepted on the CLI and for legacy profile values. Every territory also
# answers to its ISO 3166-1 code: `au` alone was unknown, and the closest
@@ -149,8 +149,8 @@ def comparable(a: str, b: str) -> bool:
territory it serves."""
return (
a == b
or _PARENT.get(a) == b
or _PARENT.get(b) == a
or PARENT.get(a) == b
or PARENT.get(b) == a
or a in AREA_TERRITORIES.get(b, ())
or b in AREA_TERRITORIES.get(a, ())
)
+1 -1
View File
@@ -74,7 +74,7 @@ def list_release_pack_platforms(platforms_dir: str = "platforms") -> list[str]:
VERSIONS_FILE = "data/.versions.json"
def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]:
def load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]:
path = Path(versions_path)
if not path.exists():
return {}
+6 -6
View File
@@ -6,7 +6,7 @@ the BIOS folder, each folder with the system name the OS gives it, the
extensions it lists and the core it starts by default. Those files hold the
OS's facts only. Which repository system a folder is, and which profile its
core is, is decided here, through the one alias table in model/systems.py
(`SYSTEM_ALIASES`, `_norm_system_id`) and the profiles' `cores:` lists, so a
(`SYSTEM_ALIASES`, `norm_system_id`) and the profiles' `cores:` lists, so a
change to either reaches every setup without a rescrape.
"""
@@ -16,7 +16,7 @@ import re
from dataclasses import dataclass, field
from pathlib import Path
from model.systems import _norm_system_id
from model.systems import norm_system_id
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles, preferred_profile, upstream_profile_index
from model.platforms import load_platform_config, native_layer
@@ -70,7 +70,7 @@ class SystemResolver:
The universe is every system a profile or a platform file names. A name
resolves, in this order, as one of those ids, as a name a platform's own
file gives a system (`native_system`, the folder Batocera calls `psx`),
or through `_norm_system_id`, which applies SYSTEM_ALIASES then drops the
or through `norm_system_id`, which applies SYSTEM_ALIASES then drops the
maker prefix and separators. A name nothing matches stays unresolved:
a new abbreviation goes into SYSTEM_ALIASES, never into a table here.
@@ -89,7 +89,7 @@ class SystemResolver:
def __post_init__(self) -> None:
for sid in self.ids:
self.by_norm.setdefault(_norm_system_id(sid), set()).add(sid)
self.by_norm.setdefault(norm_system_id(sid), set()).add(sid)
for members in self.by_norm.values():
best = min(members, key=lambda s: (-self.profile_use.get(s, 0), -len(s), s))
for sid in members:
@@ -123,7 +123,7 @@ class SystemResolver:
def equivalents(self, sid: str) -> set[str]:
"""Every id spelling the same machine as sid, sid included."""
return set(self.by_norm.get(_norm_system_id(sid), ())) | {sid}
return set(self.by_norm.get(norm_system_id(sid), ())) | {sid}
def _answer(self, found: set[str], basis: str) -> Resolution:
return Resolution(sorted({self.canonical(s) for s in found}), basis)
@@ -139,7 +139,7 @@ class SystemResolver:
own = self.native.get(platform, {}).get(lowered)
if own and len(own) == 1:
return self._answer(own, f"native name of {platform}")
norm = self.by_norm.get(_norm_system_id(lowered))
norm = self.by_norm.get(norm_system_id(lowered))
if norm:
return self._answer(norm, "normalized id")
claimed = [
+3 -5
View File
@@ -13,14 +13,12 @@ from pathlib import Path
from core.paths import REPO_ROOT
ROOT = REPO_ROOT
@dataclass(frozen=True)
class SiteInputs:
db: Path = ROOT / "database.json"
emulators: Path = ROOT / "emulators"
platforms: Path = ROOT / "platforms"
db: Path = REPO_ROOT / "database.json"
emulators: Path = REPO_ROOT / "emulators"
platforms: Path = REPO_ROOT / "platforms"
_current = [SiteInputs()]
+6 -6
View File
@@ -13,7 +13,7 @@ from typing import Iterable, Iterator
_REF_RE = re.compile(r"^(?P<path>[^:]+?)(?::(?P<start>\d+)(?:-(?P<end>\d+))?)?$")
_BARE_RANGE_RE = re.compile(r"^:?(\d+(?:-\d+)?)$")
_SPLIT_RE = re.compile(r"[,;]")
_ANNOTATION_RE = re.compile(r"\s*\([^)]*\)?")
ANNOTATION_RE = re.compile(r"\s*\([^)]*\)?")
_LOCATED_RE = re.compile(r"^[^\s:]+:\d+(?:-\d+)?$")
@@ -28,7 +28,7 @@ REPO_ROLES = ("source", "upstream")
_BINARY_SUFFIXES = (
".dll", ".exe", ".so", ".dylib", ".apk", ".elf", ".o", ".a", ".jar", ".dex",
)
_HEX_ADDRESS_RE = re.compile(r"\b0x[0-9a-fA-F]{2,}")
HEX_ADDRESS_RE = re.compile(r"\b0x[0-9a-fA-F]{2,}")
def is_binary_citation(path: str) -> bool:
@@ -39,7 +39,7 @@ def is_binary_citation(path: str) -> bool:
of any repository holds those bytes, so the ref can neither anchor nor
break: 77 parts of `future-pinball-fploader` alone were reported GONE.
"""
if _HEX_ADDRESS_RE.search(path):
if HEX_ADDRESS_RE.search(path):
return True
if " " not in path:
# A bare `DesktopKinect.dll` names a shipped library, never a source
@@ -108,7 +108,7 @@ def split_source_ref(ref: str) -> list[RefPart]:
"""
parts: list[RefPart] = []
for raw in split_outside_parentheses(str(ref or "")):
chunk = _trim_prose(_ANNOTATION_RE.sub("", raw).strip())
chunk = trim_prose(ANNOTATION_RE.sub("", raw).strip())
if not chunk:
continue
bare = _BARE_RANGE_RE.match(chunk)
@@ -206,7 +206,7 @@ def split_outside_parentheses(text: str) -> list[str]:
return [c for c in (chunk.strip() for chunk in chunks) if c]
def _trim_prose(chunk: str) -> str:
def trim_prose(chunk: str) -> str:
"""Drop a trailing comment written without parentheses.
`libretro.cpp:1520-1521 candidates_a1200` cites a location followed by a
@@ -445,7 +445,7 @@ def _run_spans(line: str, match: re.Match) -> tuple[list[tuple[int, int]], int]:
return spans, end
def _prose_runs(
def prose_runs(
text: str, known: frozenset[str] | set[str] = frozenset()
) -> Iterator[tuple[
int, tuple[int, int], tuple[tuple[int, int], ...], tuple[RefPart, ...], str, int
+32 -32
View File
@@ -3,27 +3,27 @@
from __future__ import annotations
from model import siteinputs
from model.collection import SECTION_LABELS, _PROGRAM_TOPS, _slug
from model.collection import SECTION_LABELS, PROGRAM_TOPS, manufacturer_slug
# (manufacturer slug, console) -> the id of the console's heading. Two
# folders spelled alike (Sega's "Mega CD" and "Mega-CD") share a slug, and
# the second heading took "mega-cd_1" while every link said "mega-cd".
_console_anchors: dict[tuple[str, str], str] = {}
console_anchors: dict[tuple[str, str], str] = {}
_boards_built = [False]
boards_built = [False]
# Every (manufacturer, console) section the system pages carry.
_section_pairs: set[tuple[str, str]] = set()
section_pairs: set[tuple[str, str]] = set()
# Normalized id -> the console sections spelled that way.
_console_sections: dict[str, set[tuple[str, str]]] = {}
# A console section by the name its heading reads (Bandai WonderSwan).
_sections_by_name: dict[str, set[tuple[str, str]]] = {}
sections_by_name: dict[str, set[tuple[str, str]]] = {}
# Emulator and engine names. A heading spelled like one (Game Engines >
# Solarus, ZC > ZC210) files that program's copies and names no system.
_program_names: set[str] = set()
known_program_names: set[str] = set()
def program_names(profiles: dict[str, dict]) -> set[str]:
@@ -48,7 +48,7 @@ def set_console_sections(
group them, or is a set of (manufacturer, console) pairs. ``programs``
are the emulator names, which never name a system.
"""
from model.systems import _norm_system_id
from model.systems import norm_system_id
pairs = (
{(mfr, console) for mfr, consoles in sections.items() for console in consoles}
@@ -59,40 +59,40 @@ def set_console_sections(
# system pages file them under Acorn (sitegen.systempages.arcade_board_sections).
makers = {mfr for mfr, _console in pairs}
pairs |= {parent for parent in SYSTEM_PARENTS.values()
if parent[0] in makers and parent[0] not in _PROGRAM_TOPS}
from core.anchors import _unique, toc_slug
if parent[0] in makers and parent[0] not in PROGRAM_TOPS}
from core.anchors import unique_anchor, toc_slug
_console_sections.clear()
_sections_by_name.clear()
_console_anchors.clear()
_section_pairs.clear()
_section_pairs.update(pairs)
sections_by_name.clear()
console_anchors.clear()
section_pairs.clear()
section_pairs.update(pairs)
by_maker: dict[str, list[str]] = {}
for mfr, console in pairs:
by_maker.setdefault(mfr, []).append(console)
for name in {_heading_name(mfr, console).casefold(), console.casefold()}:
_sections_by_name.setdefault(name, set()).add((mfr, console))
for name in {heading_name(mfr, console).casefold(), console.casefold()}:
sections_by_name.setdefault(name, set()).add((mfr, console))
# In the order the page lists them, after the page title's own id.
for mfr, consoles in by_maker.items():
used = {toc_slug(mfr)}
for console in sorted(consoles):
_console_anchors[(_slug(mfr), console)] = _unique(toc_slug(console), used)
console_anchors[(manufacturer_slug(mfr), console)] = unique_anchor(toc_slug(console), used)
for mfr, console in pairs:
spelled = console.lower().replace(" ", "-")
slug = mfr.lower().replace(" ", "-")
for key in {_norm_system_id(f"{slug}-{spelled}"), _norm_system_id(spelled)}:
for key in {norm_system_id(f"{slug}-{spelled}"), norm_system_id(spelled)}:
_console_sections.setdefault(key, set()).add((mfr, console))
_program_names.clear()
_program_names.update(name.casefold() for name in programs)
known_program_names.clear()
known_program_names.update(name.casefold() for name in programs)
_sections_installed[0] = True
# Which ids are boards depends on which have a section elsewhere.
_boards_built[0] = False
boards_built[0] = False
_sections_installed = [False]
def _ensure_console_sections() -> None:
def ensure_console_sections() -> None:
"""Read the sections from the repository when no generator installed
them, so a page rendered on its own names systems as the site does."""
if _sections_installed[0]:
@@ -100,26 +100,26 @@ def _ensure_console_sections() -> None:
import json
from model.profiles import load_emulator_profiles
from model.collection import _group_by_manufacturer
from model.collection import group_by_manufacturer
inputs = siteinputs.current()
with open(inputs.db, encoding="utf-8") as handle:
db = json.load(handle)
profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False)
set_console_sections(_group_by_manufacturer(db), program_names(profiles))
set_console_sections(group_by_manufacturer(db), program_names(profiles))
def _own_section(sys_id: str) -> tuple[str, str] | None:
def own_section(sys_id: str) -> tuple[str, str] | None:
"""The console section that is this id's own, or None.
Of two sections spelled alike (Atari and Camputers both file a Lynx),
the one under the maker the id names is kept. Two left is no answer,
and neither is a section that files a program's copies.
"""
from model.systems import _norm_system_id
from model.systems import norm_system_id
_ensure_console_sections()
places = _console_sections.get(_norm_system_id(sys_id), set())
ensure_console_sections()
places = _console_sections.get(norm_system_id(sys_id), set())
if len(places) > 1:
places = {
(mfr, console) for mfr, console in places
@@ -131,15 +131,15 @@ def _own_section(sys_id: str) -> tuple[str, str] | None:
# A folder under a program's top, named like its own page (Dinothawr) or
# like an emulator holds a program's files, not a system's.
if (
mfr in _PROGRAM_TOPS
mfr in PROGRAM_TOPS
or console.casefold() == mfr.casefold()
or _heading_name(mfr, console).casefold() in _program_names
or heading_name(mfr, console).casefold() in known_program_names
):
return None
return mfr, console
def _heading_name(mfr: str, console: str) -> str:
def heading_name(mfr: str, console: str) -> str:
"""A console heading read out of its page: the maker in front, unless
the heading already starts with it or the page is a game publisher's."""
from model.composition import GAME_DATA_TOPS
@@ -154,9 +154,9 @@ def _heading_name(mfr: str, console: str) -> str:
def system_name(sys_id: str) -> str:
"""The display name of a system id, the only one a page prints."""
sys_id = str(sys_id)
section = _own_section(sys_id)
section = own_section(sys_id)
if section is not None:
return _heading_name(*section)
return heading_name(*section)
name = SYSTEM_NAMES.get(sys_id)
if name is None:
raise KeyError(
+6 -6
View File
@@ -204,7 +204,7 @@ SYSTEM_ALIASES: dict[str, str] = {
@functools.cache
def _norm_system_id(sid: str) -> str:
def norm_system_id(sid: str) -> str:
"""Normalize system ID for cross-platform matching.
Resolves known aliases, then strips manufacturer prefixes and separators
@@ -259,10 +259,10 @@ def platform_system_names(config: dict, systems: list[str]) -> dict[str, list[st
def select_systems(systems: dict, wanted: list[str]) -> dict:
"""The systems a --system list keeps, by id or normalized id."""
norm = {_norm_system_id(s) for s in wanted}
norm = {norm_system_id(s) for s in wanted}
return {
sid: data for sid, data in systems.items()
if sid in wanted or _norm_system_id(sid) in norm
if sid in wanted or norm_system_id(sid) in norm
}
@@ -295,7 +295,7 @@ def resolve_system_arg(
by_key[_name_key(alias)] = [sid]
by_norm: dict[str, list[str]] = {}
for sid in systems:
by_norm.setdefault(_norm_system_id(sid), []).append(sid)
by_norm.setdefault(norm_system_id(sid), []).append(sid)
value = value.strip()
tokens = [value] if value.lower() in exact else value.split(",")
@@ -308,7 +308,7 @@ def resolve_system_arg(
found = (
exact.get(token.lower())
or (keyed if len(keyed) == 1 else None)
or by_norm.get(_norm_system_id(token))
or by_norm.get(norm_system_id(token))
)
if not found:
unknown.append(token)
@@ -335,6 +335,6 @@ def system_index(profiles: dict) -> dict[str, tuple[str, set[str]]]:
if p.get("type") in ("alias", "launcher") or p.get("role") == "test":
continue
for sys_id in p.get("systems", []):
key = _norm_system_id(sys_id)
key = norm_system_id(sys_id)
index.setdefault(key, (sys_id, set()))[1].add(name)
return index
+15 -15
View File
@@ -12,10 +12,10 @@ from dataclasses import dataclass, field
from pathlib import Path
from core.artifacts import set_plain_mode
from core.deterministic_zip import _FIXED_DATE_TIME
from core.deterministic_zip import FIXED_DATE_TIME
from core.hashing import compute_hashes
from core.paths import sanitize_pack_path
from packs.paths import _has_path_conflict, _register_path, placement_block
from packs.paths import has_path_conflict, register_path, placement_block
# Formats that are already compressed: deflating them again took 28 s of the
@@ -54,7 +54,7 @@ class PackRecord:
self.sources: dict[str, str] = {}
def _add_pack_member(
def add_pack_member(
zf: zipfile.ZipFile | PackRecord, source_path: str, arcname: str
) -> None:
"""Add a file to the pack with metadata that does not depend on the build.
@@ -71,7 +71,7 @@ def _add_pack_member(
zf.members.append(arcname)
zf.sources[arcname] = source_path
return
info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME)
info = zipfile.ZipInfo(filename=arcname, date_time=FIXED_DATE_TIME)
info.compress_type = _member_compression(arcname)
# The executable bit is the one permission worth carrying: the RetroDECK
# pack ships the two Voxatron engine binaries, and a user who extracts
@@ -89,7 +89,7 @@ def _add_pack_member(
shutil.copyfileobj(source, target, 1024 * 1024)
def _write_generated_member(
def write_generated_member(
zf: zipfile.ZipFile | PackRecord, arcname: str, text: str
) -> None:
"""Write a pack member the builder composes rather than copies.
@@ -102,14 +102,14 @@ def _write_generated_member(
if isinstance(zf, PackRecord):
zf.members.append(arcname)
return
info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME)
info = zipfile.ZipInfo(filename=arcname, date_time=FIXED_DATE_TIME)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
zf.writestr(info, text)
@contextlib.contextmanager
def _writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]:
def writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]:
"""A pack written beside its final name, swapped in once complete.
Opened on the final name, a rebuild truncated the previous pack at once,
@@ -137,7 +137,7 @@ PACK_DOCUMENTS = ("README.txt", "manifest.json")
@dataclass
class _Placed:
class Placed:
"""The destinations a build has taken, and the folders they open.
``fold`` is whether a case twin of a taken path counts as taken.
@@ -150,7 +150,7 @@ class _Placed:
def take(self, dest: str) -> None:
self.destinations.add(dest)
_register_path(dest, self.destinations, self.parents)
register_path(dest, self.destinations, self.parents)
if self.fold:
self.lower.add(dest.lower())
@@ -158,13 +158,13 @@ class _Placed:
return dest in self.destinations or (self.fold and dest.lower() in self.lower)
def conflicts(self, dest: str) -> bool:
return _has_path_conflict(dest, self.destinations, self.parents)
return has_path_conflict(dest, self.destinations, self.parents)
def block(self, dest: str) -> str | None:
return placement_block(dest, self.destinations, self.lower, self.parents, self.fold)
def _extract_zip_to_archive(
def extract_zip_to_archive(
source_zip: str,
dest_prefix: str,
target_zf: zipfile.ZipFile | PackRecord,
@@ -188,14 +188,14 @@ def _extract_zip_to_archive(
data = src.read(info.filename)
target_path = f"{dest_prefix}/{clean_name}" if dest_prefix else clean_name
member = zipfile.ZipInfo(
filename=target_path, date_time=_FIXED_DATE_TIME
filename=target_path, date_time=FIXED_DATE_TIME
)
member.compress_type = _member_compression(target_path)
member.external_attr = 0o100644 << 16
target_zf.writestr(member, data)
def _add_zip_to_pack(
def add_zip_to_pack(
source_zip: str,
dest_path: str,
target_zf: zipfile.ZipFile | PackRecord,
@@ -214,7 +214,7 @@ def _add_zip_to_pack(
target_zf.sources[dest_path] = source_zip
return
_check_zip_members(source_zip)
_add_pack_member(target_zf, source_zip, dest_path)
add_pack_member(target_zf, source_zip, dest_path)
def _check_zip_members(source_zip: str) -> None:
@@ -241,7 +241,7 @@ class DamagedArchiveError(OSError):
"""An archive of the collection whose members fail their own CRC."""
def _same_bytes(path: str, other: str | None) -> bool:
def same_bytes(path: str, other: str | None) -> bool:
if not other:
return False
if os.path.realpath(path) == os.path.realpath(other):
+14 -14
View File
@@ -21,9 +21,9 @@ from packs.verdicts import (
RELEASE_ASSET_PENDING,
Severity,
Status,
_SEVERITY_ORDER,
_STATUS_ORDER,
_storage_verdict,
SEVERITY_ORDER,
STATUS_ORDER,
storage_verdict,
compute_severity,
verify_entry_existence,
verify_entry_md5,
@@ -34,7 +34,7 @@ from resolve.cores import platform_scope_systems, resolve_platform_cores
from resolve.launchers import launcher_unproven
from resolve.nativemode import digest_algorithm, normalize as normalize_mode, reads_file_contents
from resolve.validation import (
_build_validation_index,
build_validation_index,
agnostic_substitute,
baseline_verdict,
build_ground_truth,
@@ -158,7 +158,7 @@ def _builder_placement(
path -> copy or None for each slot kept, a user_provided or external one
included).
"""
from packs.paths import _has_path_conflict, _register_path
from packs.paths import has_path_conflict, register_path
shipped: dict[str, str] = {}
occupied: dict[str, str | None] = {}
@@ -172,10 +172,10 @@ def _builder_placement(
if (
full in occupied
or (case_insensitive and full.lower() in folded)
or _has_path_conflict(full, seen, parents)
or has_path_conflict(full, seen, parents)
):
continue
_register_path(full, seen, parents)
register_path(full, seen, parents)
folded.add(full.lower())
occupied[full] = local
if local is not None:
@@ -414,7 +414,7 @@ class _PlatformTally:
"""The declaration's result, and the local copy the pack writes for it."""
config = self.run.config
mode = self.run.mode
stored = _storage_verdict(file_entry, emulator_pack=False)
stored = storage_verdict(file_entry, emulator_pack=False)
if resolve_status == RELEASE_ASSET_PENDING:
# Counted as an online build counts it, which fetches the
# asset. Under --offline the builder cannot, and neither
@@ -496,11 +496,11 @@ class _PlatformTally:
return
del self.file_status[dest], self.file_severity[dest]
prev = None
if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(prev, 0):
if prev is None or STATUS_ORDER.get(cur, 0) > STATUS_ORDER.get(prev, 0):
self.file_status[dest] = cur
self.file_required[dest] = required
prev_sev = self.file_severity.get(dest)
if prev_sev is None or _SEVERITY_ORDER.get(sev, 0) > _SEVERITY_ORDER.get(
if prev_sev is None or SEVERITY_ORDER.get(sev, 0) > SEVERITY_ORDER.get(
prev_sev, 0
):
self.file_severity[dest] = sev
@@ -819,7 +819,7 @@ def verify_platform(
for f in profile.get("files", [])
if f.get("hle_fallback")
}
validation_index = _build_validation_index(platform_profiles)
validation_index = build_validation_index(platform_profiles)
validation_owners = destination_owners(platform_profiles)
verify_systems = platform_scope_systems(config, profiles, target_cores, system_filter)
@@ -906,11 +906,11 @@ def verify_platform(
# (base_destination stripped, as the builder flattens it). The pipeline
# compares this set with the archive: equal counts can hide one file
# credited here and another written there.
from packs.paths import _flat
from packs.paths import flat_arcname
pack_destinations = sorted(
{_flat(dest, base_dest, True) for dest in shipped} | {
_flat(dest, base_dest, True) for dest in placed
{flat_arcname(dest, base_dest, True) for dest in shipped} | {
flat_arcname(dest, base_dest, True) for dest in placed
}
)
+15 -15
View File
@@ -20,15 +20,15 @@ from model.database import get_mame_clone_map
from model.declarations import OUTER_ROOTS
from model.platforms import load_platform_config
from model.registry import list_registered_platforms, load_data_dir_registry
from model.systems import _norm_system_id
from packs.gaps import _gap_destination
from model.systems import norm_system_id
from packs.gaps import gap_destination
from resolve.archives import archive_entry
from resolve.content import content_fits, name_match_size_ok
from resolve.directories import directory_members, expand_directory_entries
from resolve.launchers import (
LauncherLayer,
_directories as launcher_directories,
_names as launcher_names,
record_directories as launcher_directories,
record_names as launcher_names,
bound_launchers,
catalogued_model_files,
held_record,
@@ -39,7 +39,7 @@ from resolve.launchers import (
)
from resolve.layout import system_dir_path
from resolve.localfile import resolve_local_file
from resolve.ownership import _foreign_tree, _owner_tokens
from resolve.ownership import foreign_tree, owner_tokens
from resolve.standalone import platform_layouts
from resolve.validation import (
case_folded_slots,
@@ -80,11 +80,11 @@ def load_platform_files(
for fe in system.get("files", []):
name = fe.get("name", "")
if name:
declared.setdefault(_norm_system_id(sys_id), set()).add(name)
declared.setdefault(norm_system_id(sys_id), set()).add(name)
for dd in system.get("data_directories", []):
ref = dd.get("ref", "")
if ref:
platform_data_dirs.setdefault(_norm_system_id(sys_id), set()).add(ref)
platform_data_dirs.setdefault(norm_system_id(sys_id), set()).add(ref)
return declared, platform_data_dirs
@@ -130,7 +130,7 @@ def folded_declared_slots(
return frozenset(slots)
def _build_supplemental_index(
def build_supplemental_index(
data_root: str = "data", bios_root: str = "bios"
) -> set[str]:
"""Build a set of filenames and directory names in data/ and inside bios/ ZIPs.
@@ -214,7 +214,7 @@ def _resolve_source(
refuse it.
"""
declared = _declared_content(file_entry or {})
owners = _owner_tokens(file_entry or {})
owners = owner_tokens(file_entry or {})
def _can_be(sha1s: list | str) -> bool:
if not file_entry or db_files is None:
@@ -237,7 +237,7 @@ def _resolve_source(
return _can_be([
sha1 for sha1 in by_name.get(name) or []
if db_files is None
or not _foreign_tree(db_files.get(sha1, {}).get("path", ""), owners)
or not foreign_tree(db_files.get(sha1, {}).get("path", ""), owners)
])
# bios/ via database.json by_name
@@ -660,7 +660,7 @@ def _resolve_archive_source(
return result if result is not None else "missing"
def _first_hash(entry: dict) -> str:
def first_hash(entry: dict) -> str:
"""The first hash an entry declares, strongest first, or ''."""
for field in ("sha1", "sha256", "md5", "crc32"):
value = entry.get(field)
@@ -761,7 +761,7 @@ class _ProfileComparison:
# takes it: Batocera's standalone Cemu reads keys.txt at
# standalone_path, and the libretro Cemu/keys.txt reported here
# settled the declaration on a slot the platform never fills.
effective_path = _gap_destination(f, fname, is_standalone, save_root)
effective_path = gap_destination(f, fname, is_standalone, save_root)
slot = slot_key(f, is_standalone)
seen_key = slot
if len(self.layouts) > 1:
@@ -907,7 +907,7 @@ class _ProfileComparison:
"in_repo": in_repo,
"source": source,
# What tells this file from a homonym another emulator wants.
"identity": _first_hash(f),
"identity": first_hash(f),
}
if save_root:
entry["root"] = "save"
@@ -1011,7 +1011,7 @@ def _cross_reference_profile(
else:
platform_names = set()
for sys_id in systems:
platform_names.update(declared.get(_norm_system_id(sys_id), set()))
platform_names.update(declared.get(norm_system_id(sys_id), set()))
# The build a platform runs decides which entries it reads, as in
# find_undeclared_files: without a platform, the libretro build.
@@ -1108,7 +1108,7 @@ PLATFORM_OWN_FOLDERS = frozenset({"<emulatorLauncher folder>"})
def launcher_file_names(record: dict) -> list[str]:
"""The concrete file names a launcher record reads, in code order.
The names are read as the launcher layer reads them (`launchers._names`):
The names are read as the launcher layer reads them (`launchers.record_names`):
a label after the name is dropped ("neocd_z.rom (CDZ)"), and a name with
`<` or without an extension is not a file name (a folder the record
links, an option value such as hatari2014's "default"). A name with a
+5 -5
View File
@@ -24,7 +24,7 @@ from core.artifacts import file_lock as _file_lock, set_plain_mode
from core.cli import InputMissing
from core.github import github_token
from model.safeparse import yaml_load
from model.registry import VERSIONS_FILE, _load_versions
from model.registry import VERSIONS_FILE, load_versions
log = logging.getLogger(__name__)
@@ -155,7 +155,7 @@ def _record_version(key: str, record: dict, versions_path: str) -> None:
"""Set one key under the file lock, so two writers keep both updates."""
path = Path(versions_path)
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
versions = load_versions(versions_path)
versions[key] = record
_save_versions(versions, versions_path)
@@ -437,7 +437,7 @@ def _record_archive_size(key: str, entry: dict, versions_path: str) -> None:
"""
path = Path(versions_path)
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
versions = load_versions(versions_path)
record = versions.get(key)
if record is None or "archive_size" in record:
return
@@ -446,7 +446,7 @@ def _record_archive_size(key: str, entry: dict, versions_path: str) -> None:
if size is None:
return
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = _load_versions(versions_path)
versions = load_versions(versions_path)
if key in versions and "archive_size" not in versions[key]:
versions[key]["archive_size"] = size
_save_versions(versions, versions_path)
@@ -513,7 +513,7 @@ def _decide(
"""(whether the tree needs a refresh, the remote tag read, the recorded
tag). None when the remote could not be read."""
version = entry.get("version", "master")
cached = _load_versions(versions_path).get(key, {})
cached = load_versions(versions_path).get(key, {})
cached_tag = cached.get("sha") or cached.get("etag")
if force or not Path(entry["local_cache"]).exists():
return True, None, cached_tag
+18 -18
View File
@@ -13,11 +13,11 @@ from core.hashing import compute_hashes
from core.options import reject_unknown
from model.declarations import declared_root
from model.profiles import entry_system_ids, installed_data_refs
from model.systems import _norm_system_id
from packs.archive import PackRecord, _add_pack_member
from model.systems import norm_system_id
from packs.archive import PackRecord, add_pack_member
from packs.datadirs import cache_lock
from packs.extras import prefixed_destination
from packs.paths import MEDIA_MARKER, _has_path_conflict, _register_path, lands_on_android
from packs.paths import MEDIA_MARKER, has_path_conflict, register_path, lands_on_android
from resolve.cores import resolve_platform_cores as _platform_cores
from resolve.layout import core_system_dirs
from resolve.standalone import platform_layouts, standalone_set
@@ -113,7 +113,7 @@ def core_data_trees(
return trees
def _in_data_cache(path: str, data_registry: dict | None) -> bool:
def in_data_cache(path: str, data_registry: dict | None) -> bool:
"""Whether a resolved file lies in one of the data directory caches."""
real = os.path.realpath(path)
return any(
@@ -136,7 +136,7 @@ def _tree_references(
class _TreeWalkOptions(TypedDict, total=False):
"""The keyword options of _data_directory_members."""
"""The keyword options of data_directory_members."""
refs_out: dict | None
required_only: bool
@@ -160,7 +160,7 @@ def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> s
print(
f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)"
)
_MISSING_DATA_DIRS.add(ref_key)
MISSING_DATA_DIRS.add(ref_key)
return None
return local_path
@@ -174,7 +174,7 @@ def _tree_files(local_path: str, dd_prefix: str) -> Iterator[tuple[str, str]]:
yield src, f"{dd_prefix}/{rel}" if dd_prefix else rel
def _data_directory_members(
def data_directory_members(
pack_systems: dict,
data_registry: dict | None,
platform_name: str,
@@ -205,7 +205,7 @@ def _data_directory_members(
``required_only`` leaves out a tree declared ``required: false``, one the
core runs without, as it leaves out such a file.
"""
reject_unknown("_data_directory_members", options, _TreeWalkOptions.__optional_keys__)
reject_unknown("data_directory_members", options, _TreeWalkOptions.__optional_keys__)
refs_out = options.get("refs_out")
reclaim = options.get("reclaim")
required_only = options.get("required_only", False)
@@ -231,11 +231,11 @@ def _data_directory_members(
del reclaim[full]
elif full in seen_destinations or (
full.lower() in seen_lower and case_insensitive
) or _has_path_conflict(full, seen_destinations, seen_parents):
) or has_path_conflict(full, seen_destinations, seen_parents):
continue
else:
seen_destinations.add(full)
_register_path(full, seen_destinations, seen_parents)
register_path(full, seen_destinations, seen_parents)
if case_insensitive:
seen_lower.add(full.lower())
if refs_out is not None:
@@ -243,7 +243,7 @@ def _data_directory_members(
yield src, full
def _pack_data_tree(
def pack_data_tree(
zf: zipfile.ZipFile | PackRecord,
local_cache: str,
dd_dest: str,
@@ -266,14 +266,14 @@ def _pack_data_tree(
src = os.path.join(root, fname)
rel = os.path.relpath(src, local_cache)
full = f"{dd_dest}/{rel}" if dd_dest else rel
if full.lower() in seen_lower or _has_path_conflict(
if full.lower() in seen_lower or has_path_conflict(
full, seen_destinations, seen_parents
):
continue
seen_destinations.add(full)
_register_path(full, seen_destinations, seen_parents)
register_path(full, seen_destinations, seen_parents)
seen_lower.add(full.lower())
_add_pack_member(zf, src, full)
add_pack_member(zf, src, full)
if packed_at is not None:
packed_at[full.lower()] = src
added += 1
@@ -283,7 +283,7 @@ def _pack_data_tree(
# Data directories a pack needed and the cache did not hold. The pack is
# written without them, so the run cannot exit as if it were complete: a
# refresh refused by a quota left the PPSSPP pack with 2 files, exit 0.
_MISSING_DATA_DIRS: set[str] = set()
MISSING_DATA_DIRS: set[str] = set()
def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, list[str]]:
@@ -341,7 +341,7 @@ def _tree_group(
return group
def _manifest_data_directories(
def manifest_data_directories(
members: list[tuple[str, str]],
refs: dict[str, tuple[str, tuple[str, ...], str, bool]],
registry: dict,
@@ -373,11 +373,11 @@ def _manifest_data_directories(
versions: dict[str, dict[str, dict]] = {}
by_norm: dict[str, list[str]] = {}
for sys_id in sorted(platform_systems or ()):
by_norm.setdefault(_norm_system_id(sys_id), []).append(sys_id)
by_norm.setdefault(norm_system_id(sys_id), []).append(sys_id)
for src, full in members:
ref, systems, prefix, needed = refs[full]
if platform_systems is not None:
systems = tuple(own for sid in systems for own in by_norm.get(_norm_system_id(sid), ()))
systems = tuple(own for sid in systems for own in by_norm.get(norm_system_id(sid), ()))
key = (ref, prefix)
group = grouped.get(key)
if group is None:
+21 -21
View File
@@ -26,15 +26,15 @@ from packs.verdicts import (
RELEASE_ASSET_PENDING,
Severity,
Status,
_SEVERITY_ORDER,
_STATUS_ORDER,
_emulator_severity,
_storage_verdict,
SEVERITY_ORDER,
STATUS_ORDER,
emulator_severity,
storage_verdict,
)
from resolve.archives import archive_entry, archive_is_optional
from resolve.directories import expand_directory_entries
from resolve.validation import (
_build_validation_index,
build_validation_index,
build_ground_truth,
deliverable,
validated_choice,
@@ -111,7 +111,7 @@ def _emulator_files(
) -> list[dict]:
"""The entries of a profile the emulator pack carries."""
from packs.extras import expand_agnostic_entries
from packs.paths import _resolve_destination
from packs.paths import resolve_destination
files = expand_agnostic_entries(
expand_directory_entries(
@@ -142,7 +142,7 @@ def _emulator_files(
fe
for fe in files
if fe.get("archive")
or _resolve_destination(fe, standalone) not in region_drops
or resolve_destination(fe, standalone) not in region_drops
]
return files
@@ -251,12 +251,12 @@ class _EmulatorPack:
)
def occupy(self, dest: str, path: str | None, owner: str) -> None:
from packs.paths import _register_path
from packs.paths import register_path
if self.block(dest):
return
self.placed[dest.lower()] = (path, owner, dest)
_register_path(dest, self.placed_files, self.placed_parents)
register_path(dest, self.placed_files, self.placed_parents)
def occupy_trees(self, emu_name: str, profile: dict) -> None:
"""The profile's data trees follow its files in the pack, which
@@ -331,7 +331,7 @@ class _EmulatorPack:
self, emu_name: str, profile: dict, files: list[dict], spares: set[str],
) -> list[PlacedResult]:
# Verify archives as units (e.g., neogeo.zip, aes.zip)
from packs.paths import _archive_destination
from packs.paths import archive_destination
from resolve.packfiles import resolve_file
placed_results: list[PlacedResult] = []
@@ -344,7 +344,7 @@ class _EmulatorPack:
own_entry = archive_entry(archive, files)
# Where the pack puts it: an archive_prefix or pack_structure
# moves it, and a loose same-named entry is another file.
dest = _archive_destination(
dest = archive_destination(
archive, profile.get("archive_prefix", ""),
profile.get("pack_structure"), self.standalone,
)
@@ -387,7 +387,7 @@ class _EmulatorPack:
def _loose_results(
self, emu_name: str, files: list[dict],
) -> dict[str, list[tuple[dict, bool, bool, dict]]]:
from packs.paths import _resolve_destination
from packs.paths import resolve_destination
from resolve.packfiles import resolve_file
# Results of this emulator, by destination. Several entries of one
@@ -426,7 +426,7 @@ class _EmulatorPack:
result["ground_truth"] = build_ground_truth(name, self.validation_index)
# The slot the emulator pack places this entry in: standalone_path
# under --standalone, the sanitised path.
dest = _resolve_destination(file_entry, self.standalone) or name
dest = resolve_destination(file_entry, self.standalone) or name
emu_results.setdefault(dest, []).append((result, required, hle, file_entry))
return emu_results
@@ -435,7 +435,7 @@ class _EmulatorPack:
resolve_status: str, emu_name: str,
) -> dict:
"""The verdict on a loose profile entry, from its resolution."""
stored = _storage_verdict(file_entry, emulator_pack=True)
stored = storage_verdict(file_entry, emulator_pack=True)
if stored is not None:
return stored
if resolve_status == RELEASE_ASSET_PENDING:
@@ -589,15 +589,15 @@ class _EmulatorPack:
self.dest_to_name[dest] = result["name"]
cur = result["status"]
prev = self.file_status.get(dest)
if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(
if prev is None or STATUS_ORDER.get(cur, 0) > STATUS_ORDER.get(
prev, 0
):
self.file_status[dest] = cur
sev = _emulator_severity(cur, required, hle)
sev = emulator_severity(cur, required, hle)
prev_sev = self.file_severity.get(dest)
if prev_sev is None or _SEVERITY_ORDER.get(
if prev_sev is None or SEVERITY_ORDER.get(
sev, 0
) > _SEVERITY_ORDER.get(prev_sev, 0):
) > SEVERITY_ORDER.get(prev_sev, 0):
self.file_severity[dest] = sev
@@ -632,7 +632,7 @@ def verify_emulator(
file or tree marked ``required: false`` is left out, and an archive when
it and every member it carries are optional, as the builder leaves them.
"""
from packs.paths import _resolve_destination
from packs.paths import resolve_destination
# Also load aliases for redirect messages
all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
@@ -649,7 +649,7 @@ def verify_emulator(
# Build validation index from selected profiles only
selected_profiles = dict(selected)
validation_index = _build_validation_index(selected_profiles)
validation_index = build_validation_index(selected_profiles)
data_registry = load_data_dir_registry(platforms_dir)
pack = _EmulatorPack(
@@ -681,7 +681,7 @@ def verify_emulator(
)
files = [
fe for fe in files
if fe.get("archive") or _resolve_destination(fe, standalone) not in spares
if fe.get("archive") or resolve_destination(fe, standalone) not in spares
]
pack.verify_profile(emu_name, profile, files, spares)
+29 -29
View File
@@ -29,23 +29,23 @@ from model.registry import load_data_dir_registry
from model.systems import MANUFACTURER_PREFIXES, system_index
from packs.archive import (
PackRecord,
_Placed,
_add_pack_member,
_add_zip_to_pack,
_same_bytes,
_write_generated_member,
_writing_pack,
Placed,
add_pack_member,
add_zip_to_pack,
same_bytes,
write_generated_member,
writing_pack,
)
from packs.datatrees import _MISSING_DATA_DIRS, _pack_data_tree
from packs.datatrees import MISSING_DATA_DIRS, pack_data_tree
from packs.extras import emulator_region_drops, emulator_required_spares, expand_agnostic_entries
from packs.naming import _bounded_join, _bounded_pack_name, _name_part, _narrowings
from packs.paths import _archive_destination, _resolve_destination
from packs.naming import bounded_join, bounded_pack_name, file_name_part, pack_narrowings
from packs.paths import archive_destination, resolve_destination
from resolve import packfiles as packresolve
from resolve.archives import archive_entry, archive_is_optional
from resolve.directories import expand_directory_entries
from resolve.packfiles import download_external, resolve_file
from resolve.validation import (
_build_validation_index,
build_validation_index,
deliverable,
validated_choice,
with_archive_members,
@@ -100,7 +100,7 @@ class _EmulatorPackBuild:
discrepancies: list[str] = field(default_factory=list)
unsourceable_files: list[str] = field(default_factory=list)
instruction_files: list[str] = field(default_factory=list)
placed: _Placed = field(default_factory=lambda: _Placed(True))
placed: Placed = field(default_factory=lambda: Placed(True))
seen_hashes: set[str] = field(default_factory=set) # SHA1 dedup for same file, different path
# Loose file packed at each folded destination, to tell a profile asking
# for the same file there from one asking for other bytes.
@@ -118,9 +118,9 @@ class _EmulatorPackBuild:
def _add(self, local_path: str, dest: str, fe: dict | None) -> None:
"""Write a loose file or an archive at dest and count it."""
if fe is not None and local_path.endswith(".zip"):
_add_zip_to_pack(local_path, dest, self.zf, fe)
add_zip_to_pack(local_path, dest, self.zf, fe)
else:
_add_pack_member(self.zf, local_path, dest)
add_pack_member(self.zf, local_path, dest)
self.placed.take(dest)
self.total_files += 1
if self.record is not None:
@@ -156,7 +156,7 @@ class _EmulatorPackBuild:
# Pack archives as units
archive_prefix = profile.get("archive_prefix", "")
for archive_name in sorted({fe["archive"] for fe in files if fe.get("archive")}):
archive_dest = _archive_destination(
archive_dest = archive_destination(
archive_name, archive_prefix, pack_structure, self.standalone
)
own_entry = archive_entry(archive_name, files)
@@ -196,7 +196,7 @@ class _EmulatorPackBuild:
# profile without its archive, which used to pass in
# silence: a neocdz.zip lacking 000-lo.lo shipped as the
# one the second core needs.
if not (taken and local_path and _same_bytes(
if not (taken and local_path and same_bytes(
local_path, self.packed_at.get(archive_dest.lower())
)):
return ([own_entry], False, functools.partial(
@@ -223,7 +223,7 @@ class _EmulatorPackBuild:
continue
if fe.get("archive"):
continue
dest = _resolve_destination(fe, self.standalone)
dest = resolve_destination(fe, self.standalone)
if not dest or dest in spares:
continue
if self.region_drops and dest in self.region_drops:
@@ -237,7 +237,7 @@ class _EmulatorPackBuild:
self.placed.take(dest)
instr = provided.get("instructions", "Please provide this file manually.")
folder = dest.rsplit("/", 1)[0] + "/" if "/" in dest else ""
_write_generated_member(
write_generated_member(
self.zf,
f"{folder}INSTRUCTIONS_{provided['name']}.txt",
f"File needed: {provided['name']}\n\n{instr}\n",
@@ -314,7 +314,7 @@ class _EmulatorPackBuild:
else None if chosen is not None else refused_path
)
if chosen is not None or held is not None:
if block == "taken" and held and _same_bytes(
if block == "taken" and held and same_bytes(
held, self.packed_at.get(dest.lower())
):
# The file already at this path, asked for twice.
@@ -400,7 +400,7 @@ class _EmulatorPackBuild:
prefix = pack_structure.get(mode_key, "")
if prefix:
dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix
self.data_files += _pack_data_tree(
self.data_files += pack_data_tree(
self.zf, local_cache, dd_dest, self.placed.destinations,
self.placed.parents, self.placed.lower, self.packed_at,
)
@@ -441,7 +441,7 @@ class _EmulatorPackBuild:
print(
f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)"
)
_MISSING_DATA_DIRS.update(self.data_dir_notices)
MISSING_DATA_DIRS.update(self.data_dir_notices)
def generate_emulator_pack(
@@ -483,15 +483,15 @@ def generate_emulator_pack(
record = options.get("record")
# ZIP naming
display_names = [_name_part(p.get("emulator", n)) for n, p in selected]
validation_index = _build_validation_index(dict(selected))
display_names = [file_name_part(p.get("emulator", n)) for n, p in selected]
validation_index = build_validation_index(dict(selected))
narrow_tags = "".join(
tag
for tag, _label in _narrowings(
for tag, _label in pack_narrowings(
"full", regions, None, False, required_only, standalone
)
)
zip_name = options.get("pack_name") or _bounded_pack_name(
zip_name = options.get("pack_name") or bounded_pack_name(
display_names, [n for n, _p in selected], f"{narrow_tags}_BIOS_Pack.zip"
)
zip_path = os.path.join(output_dir, zip_name)
@@ -511,7 +511,7 @@ def generate_emulator_pack(
)
with (
contextlib.nullcontext(record) if record is not None
else _writing_pack(zip_path)
else writing_pack(zip_path)
) as zf:
build = _EmulatorPackBuild(
db, bios_dir, standalone, required_only, zip_contents, data_registry,
@@ -589,8 +589,8 @@ def generate_system_pack(
# Named like the platform's --system tag: one spelling of a system is
# one file name, and one selection.
sys_display = _bounded_join(
[_system_display_name(sid) for sid in system_ids], list(system_ids)
sys_display = bounded_join(
[system_display_name(sid) for sid in system_ids], list(system_ids)
)
# Built in a scratch directory: under its emulator name in output_dir it
# overwrote, then carried away, an --emulator pack already there.
@@ -599,7 +599,7 @@ def generate_system_pack(
# tag made --system X --required-only overwrite the pack built without it.
tags = "".join(
tag
for tag, _label in _narrowings(
for tag, _label in pack_narrowings(
"full", regions, None, False, required_only, standalone=standalone
)
)
@@ -634,7 +634,7 @@ def generate_system_pack(
shutil.rmtree(scratch, ignore_errors=True)
def _system_display_name(system_id: str) -> str:
def system_display_name(system_id: str) -> str:
"""Convert system ID to display name for ZIP naming."""
s = system_id.lower().replace("_", "-")
for prefix in MANUFACTURER_PREFIXES:
+37 -37
View File
@@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, TypedDict
from core.options import reject_unknown
from model.profiles import PROFILE_IDENTITY_FIELDS, entry_system_ids
from model.systems import _norm_system_id
from model.systems import norm_system_id
from model.alternatives import core_file_spares, required_only_spares, set_fields
from resolve.archives import archive_members, contents_members, holds_required_members
from model.declarations import declared_root, expand_platform_declared_names, platform_declarations
@@ -34,7 +34,7 @@ if TYPE_CHECKING:
from typing_extensions import Unpack
def _detect_extras_prefix(config: dict, base_dest: str) -> str:
def detect_extras_prefix(config: dict, base_dest: str) -> str:
"""The prefix core-extra destinations take (may be empty).
When base_destination is empty (RetroDECK), it is the dominant root of
@@ -198,7 +198,7 @@ def _map_emulator_to_slug(
sys_to_slug: dict[str, str],
) -> str:
"""Map an emulator to a destination slug for slug-based platforms."""
from model.systems import _norm_system_id
from model.systems import norm_system_id
emu_systems = set(profile.get("systems", []))
# Direct match
@@ -208,7 +208,7 @@ def _map_emulator_to_slug(
return sys_to_slug.get(target, "")
# Normalized match
for es in sorted(emu_systems):
norm = _norm_system_id(es)
norm = norm_system_id(es)
if norm in norm_map:
target = norm_map[norm]
return sys_to_slug.get(target, "")
@@ -404,7 +404,7 @@ def hidden_extras(
``required_only`` are the builder's for a --source truth or a
--required-only pack: an optional extra is skipped before it takes a path.
"""
from packs.paths import _register_path, placement_block
from packs.paths import register_path, placement_block
reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__)
report = options.get("report")
@@ -423,14 +423,14 @@ def hidden_extras(
parents: set[str] = set()
content: dict[str, str | None] = {}
for dest, local in shipped.items():
_register_path(dest, seen, parents)
register_path(dest, seen, parents)
content[dest.lower()] = sha1_by_path.get(local)
lower = set(content) if case_insensitive else set()
prefix = _detect_extras_prefix(config, base_dest)
prefix = detect_extras_prefix(config, base_dest)
region_prefix = declared_root(config)
hidden: dict[tuple[str, str, str], str] = {}
packed_keys: set[tuple[str, str, str]] = set()
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config, emulators_dir, db, set() if system_ids else set(shipped),
base_dest, profiles, target_cores=target_cores, include_all=include_all,
undeclared=report,
@@ -474,7 +474,7 @@ def hidden_extras(
hidden.setdefault(key, reason)
continue
packed_keys.add(key)
_register_path(full, seen, parents)
register_path(full, seen, parents)
content[full.lower()] = held
if case_insensitive:
lower.add(full.lower())
@@ -1275,9 +1275,9 @@ class ExtraPlacement:
"""
def __init__(self, config: dict, base_dest: str, profiles: dict) -> None:
from model.systems import _norm_system_id
from model.systems import norm_system_id
self.prefix = _detect_extras_prefix(config, base_dest)
self.prefix = detect_extras_prefix(config, base_dest)
self.slug_based, self.sys_to_slug = _detect_slug_structure(config)
self.platform_systems = set(config.get("systems", {}).keys())
self.native_systems = native_slug_systems(config)
@@ -1289,7 +1289,7 @@ class ExtraPlacement:
self.outer = {root for root in OUTER_ROOTS if outer_layout(config, root)}
self.config = config
self.norm_map = (
{_norm_system_id(sid): sid for sid in self.platform_systems}
{norm_system_id(sid): sid for sid in self.platform_systems}
if self.slug_based
else {}
)
@@ -1393,7 +1393,7 @@ def undeclared_report(
target_cores: set[str] | None = None,
include_all: bool = False,
) -> list[dict]:
"""The gap report _collect_emulator_extras reads, for a caller that
"""The gap report collect_emulator_extras reads, for a caller that
collects the extras more than once with these arguments: the region
grouping and the pack or manifest phase 2 each computed it in full."""
from packs.gaps import find_undeclared_files
@@ -1406,7 +1406,7 @@ def undeclared_report(
class CollectOptions(TypedDict, total=False):
"""The records _collect_emulator_extras fills, and the report it reuses."""
"""The records collect_emulator_extras fills, and the report it reuses."""
claimants: dict[tuple[str, str, str], str] | None
unplaceable: list[dict] | None
@@ -1447,7 +1447,7 @@ class _CopyScope:
extras_prefix: str
def _collect_emulator_extras(
def collect_emulator_extras(
config: dict,
emulators_dir: str,
db: dict,
@@ -1490,7 +1490,7 @@ def _collect_emulator_extras(
Works for ANY platform (RetroArch, Batocera, Recalbox, etc.)
"""
reject_unknown("_collect_emulator_extras", options, CollectOptions.__optional_keys__)
reject_unknown("collect_emulator_extras", options, CollectOptions.__optional_keys__)
undeclared = options.get("undeclared")
claimants = options.get("claimants")
unplaceable = options.get("unplaceable")
@@ -2042,25 +2042,25 @@ def _another_claim(extra: dict | None, claim: dict) -> None:
claims.sort(key=lambda c: c["claim_order"])
def _extra_system_ids(extra: dict) -> list[str]:
def extra_system_ids(extra: dict) -> list[str]:
"""Return the narrowest system ownership preserved on a core extra."""
explicit = extra.get("source_system")
if explicit:
return [str(explicit)]
return [str(value) for value in extra.get("source_systems", []) if value]
def _serving_system_ids(extra: dict) -> list[str]:
def serving_system_ids(extra: dict) -> list[str]:
"""Every system the extra's file serves: its own core's and those of the
other cores whose claim rides on it. One file stands per destination, so
narrowed to any of their systems the file is what that core reads.
"""
ids = list(_extra_system_ids(extra))
ids = list(extra_system_ids(extra))
for claim in extra.get("other_claims", []):
ids.extend(s for s in _extra_system_ids(claim) if s not in ids)
ids.extend(s for s in extra_system_ids(claim) if s not in ids)
return ids
def _kept(entries: list[dict], required_only: bool) -> list[dict]:
def kept_entries(entries: list[dict], required_only: bool) -> list[dict]:
"""The entries a pack keeps: optional ones go under --required-only."""
if not required_only:
return entries
@@ -2073,12 +2073,12 @@ def extras_for_systems(extras: list[dict], system_ids: list[str]) -> list[dict]:
Extras carry their profile/system identity directly. Display labels are
presentation only and must never drive routing.
"""
wanted = set(system_ids) | {_norm_system_id(s) for s in system_ids}
wanted = set(system_ids) | {norm_system_id(s) for s in system_ids}
return [
fe for fe in extras
if (
set(_serving_system_ids(fe))
| {_norm_system_id(s) for s in _serving_system_ids(fe)}
set(serving_system_ids(fe))
| {norm_system_id(s) for s in serving_system_ids(fe)}
) & wanted
]
@@ -2187,7 +2187,7 @@ def platform_region_groups(
members = groups.setdefault(sys_id, [])
# Decided over what the pack keeps: an optional winner removed
# afterwards left its slot empty.
for file_entry in _kept(system.get("files", []), required_only):
for file_entry in kept_entries(system.get("files", []), required_only):
dest = declared_destination(file_entry)
if dest:
members.append((dest, file_entry.get("name", "")))
@@ -2203,7 +2203,7 @@ def platform_region_groups(
return groups, extra_dests
absent: list[dict] = []
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config,
emulators_dir,
db,
@@ -2219,7 +2219,7 @@ def platform_region_groups(
held = {id(extra) for extra in extras}
spellings = system_spellings(systems)
region_prefix = declared_root(config)
for extra in _kept(extras + absent, required_only):
for extra in kept_entries(extras + absent, required_only):
dest = extra_region_key(extra, region_prefix)
if not dest:
continue
@@ -2255,7 +2255,7 @@ def system_spellings(systems: Iterable[str]) -> dict[str, str]:
"""
spellings: dict[str, str] = {}
for sys_id in sorted(systems):
spellings.setdefault(_norm_system_id(sys_id), sys_id)
spellings.setdefault(norm_system_id(sys_id), sys_id)
return spellings
@@ -2268,7 +2268,7 @@ def extra_region_groups(
extra competes beside the files the platform declares for that system.
"""
def system_group(sys_id: str) -> str:
return (spellings or {}).get(_norm_system_id(sys_id), sys_id)
return (spellings or {}).get(norm_system_id(sys_id), sys_id)
emulator = extra.get("source_emulator", "")
variant = extra.get("selection_slot")
@@ -2314,19 +2314,19 @@ def emulator_region_drops(
emulator pack resolves with.
"""
from resolve import regions as resolve_regions
from packs.paths import _resolve_destination
from resolve.validation import _build_validation_index, filter_files_by_mode
from packs.paths import resolve_destination
from resolve.validation import build_validation_index, filter_files_by_mode
region_index = resolve_regions.build_region_index(dict(selected))
region_groups: dict[str, list[tuple[str, str]]] = {}
held: set[str] | None = set() if db is not None else None
validation_index = _build_validation_index(dict(selected)) if db is not None else {}
validation_index = build_validation_index(dict(selected)) if db is not None else {}
for emu_name, profile in sorted(selected):
# Decided over what the pack keeps, as on the platform side: an
# optional winner removed afterwards left its slot empty.
entries = filter_files_by_mode(profile.get("files", []), standalone)
for fe in _kept(entries, required_only):
dest = _resolve_destination(fe, standalone)
for fe in kept_entries(entries, required_only):
dest = resolve_destination(fe, standalone)
if dest:
group_id = _emulator_region_group(emu_name, profile, fe, dest)
region_groups.setdefault(group_id, []).append(
@@ -2362,7 +2362,7 @@ def emulator_required_spares(
stvbios.zip. The pack and verify --emulator both read this."""
from model.alternatives import groups_of, rank_in, required_groups
from resolve.archives import archive_entry
from packs.paths import _archive_destination, _resolve_destination
from packs.paths import archive_destination, resolve_destination
reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__)
data_registry = options.get("data_registry")
@@ -2374,12 +2374,12 @@ def emulator_required_spares(
archives.append(archive)
own = archive_entry(archive, files)
if groups_of(own):
candidates.append({"dest": _archive_destination(
candidates.append({"dest": archive_destination(
archive, profile.get("archive_prefix", ""),
profile.get("pack_structure"), standalone,
), "entry": own})
candidates.extend(
{"dest": _resolve_destination(fe, standalone), "entry": fe}
{"dest": resolve_destination(fe, standalone), "entry": fe}
for fe in files if not fe.get("archive") and groups_of(fe)
)
if not candidates:
+10 -10
View File
@@ -17,16 +17,16 @@ from core.artifacts import set_plain_mode
from core.options import reject_unknown
from model.registry import list_registered_platforms
from model.targets import load_target_config
from packs.archive import _write_generated_member
from packs.archive import write_generated_member
from packs.integrity import generate_sha256sums, verify_pack, verify_pack_against_platform
from packs.naming import _expected_pack_names, _narrows_contents, _pack_archives
from packs.naming import expected_pack_names, narrows_contents, pack_archives
from packs.scope import annotate_pack_systems
if TYPE_CHECKING:
from typing_extensions import Unpack
def _baseline_shortfall(excluded: int, absent: int) -> list[str]:
def baseline_shortfall(excluded: int, absent: int) -> list[str]:
"""Why a verified pack holds fewer baseline files than the platform declares."""
parts = []
if excluded:
@@ -43,7 +43,7 @@ def inject_manifest(zip_path: str, manifest: dict) -> None:
"""Inject manifest.json into an existing ZIP pack.
The pack is rewritten beside its final name and swapped in, as
_writing_pack builds it: appending in place rewrites the central
writing_pack builds it: appending in place rewrites the central
directory last, so a process killed in between left an unreadable ZIP
where a valid pack had been.
"""
@@ -64,7 +64,7 @@ def inject_manifest(zip_path: str, manifest: dict) -> None:
# two different byte layouts depending on the path taken here.
shutil.copyfile(zip_path, scratch)
with zipfile.ZipFile(scratch, "a", zipfile.ZIP_DEFLATED) as zf:
_write_generated_member(zf, "manifest.json", manifest_json)
write_generated_member(zf, "manifest.json", manifest_json)
else:
with zipfile.ZipFile(zip_path, "r") as src, \
zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as dst:
@@ -72,7 +72,7 @@ def inject_manifest(zip_path: str, manifest: dict) -> None:
if item.filename == "manifest.json":
continue
dst.writestr(item, src.read(item.filename))
_write_generated_member(dst, "manifest.json", manifest_json)
write_generated_member(dst, "manifest.json", manifest_json)
set_plain_mode(scratch)
os.replace(scratch, zip_path)
except BaseException:
@@ -149,7 +149,7 @@ def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> b
)
status = "OK" if p_ok else "FAILED"
exclusion_note = "".join(
f", {part}" for part in _baseline_shortfall(bl_excluded, bl_absent)
f", {part}" for part in baseline_shortfall(bl_excluded, bl_absent)
)
print(
f" platform {pname}: {bl_present}/{bl_checked} baseline present"
@@ -192,11 +192,11 @@ def verify_and_finalize_packs(
# substring: a _Custom or regional pack left by another run was judged
# against this run's expectation and failed it.
registered = list_registered_platforms(opts.platforms_dir)
expected = _expected_pack_names(
expected = expected_pack_names(
registered, opts.platforms_dir, opts.regions, opts.target_name,
no_game_data=opts.no_game_data,
)
packs = _pack_archives(output_dir)
packs = pack_archives(output_dir)
if opts.built is not None:
packs = [name for name in packs if name in set(opts.built)]
pack_to_platform: dict[str, list[str]] = {}
@@ -229,7 +229,7 @@ def verify_and_finalize_packs(
# Skipped for filtered/split/custom packs (intentionally partial)
if opts.skip_conformance:
continue
if _narrows_contents(name):
if narrows_contents(name):
continue
for pname in pack_to_platform.get(name, []):
if not _conforms(zip_path, pname, db, opts):
+8 -8
View File
@@ -17,10 +17,10 @@ from resolve.launchers import LauncherLayer, declared_destinations, held_record
from resolve.layout import runs_standalone, system_dir_path
from resolve.localfile import resolve_local_file
from resolve.nativemode import hash_mismatch_excludes_file
from resolve.ownership import _foreign_tree, _owner_tokens
from resolve.ownership import foreign_tree, owner_tokens
from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set
from resolve.validation import (
_parse_validation,
parse_validation,
case_folded_slots,
core_size_refusal,
declaration_settles,
@@ -56,7 +56,7 @@ def _build_expected(file_entry: dict, checks: list[str]) -> dict:
def _in_foreign_tree(db: dict, owners: set[str], sha1: str) -> bool:
"""Whether the collection keeps this sha1 in another emulator's tree."""
return _foreign_tree(db.get("files", {}).get(sha1, {}).get("path", ""), owners)
return foreign_tree(db.get("files", {}).get(sha1, {}).get("path", ""), owners)
def _name_in_index(
@@ -137,7 +137,7 @@ def _identity_of(entry: dict) -> dict:
}
def _gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str:
def gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str:
"""The destination a gap entry is keyed and reported at."""
# One destination rule for the dedup key and for the entry: a
# standalone build without standalone_path falls back on path.
@@ -206,7 +206,7 @@ class _GapScan:
"""Consider one profile entry of one build as a gap."""
fname = f.get("name", "")
save_root = read_from_save_dir(f, is_standalone)
dest = _gap_destination(f, fname, is_standalone, save_root)
dest = gap_destination(f, fname, is_standalone, save_root)
region_key = _region_key(f)
# Same-name requirements at different paths, for different systems,
# or in distinct variant groups are not interchangeable.
@@ -350,7 +350,7 @@ class _GapScan:
_lp, _st = resolve_local_file(owned, self.db, dest_hint=dest)
return _lp is not None and _st != "hash_mismatch"
in_repo = self._held_by_name(owned, f, fname, dest)
if in_repo and "size" in _parse_validation(f.get("validation")):
if in_repo and "size" in parse_validation(f.get("validation")):
# On any platform the core measures what it opens: a
# copy it turns away by its own size check is not
# held for it, the rule the builder's lookup applies
@@ -364,7 +364,7 @@ class _GapScan:
return in_repo
def _held_by_name(self, owned: dict, f: dict, fname: str, dest: str) -> bool:
foreign = functools.partial(_in_foreign_tree, self.db, _owner_tokens(owned))
foreign = functools.partial(_in_foreign_tree, self.db, owner_tokens(owned))
in_repo = _name_in_index(
fname, self.by_name, self.by_path_suffix, self.data_names, self.by_name_lower,
foreign,
@@ -407,7 +407,7 @@ class _GapScan:
self, emu_name: str, layout: dict, f: dict, fname: str, dest: str,
in_repo: bool, save_root: bool,
) -> dict:
checks = _parse_validation(f.get("validation"))
checks = parse_validation(f.get("validation"))
entry = {
"profile": emu_name,
"emulator": layout.get("emulator", emu_name),
+8 -8
View File
@@ -11,8 +11,8 @@ from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from packs.verdicts import DEFAULT_BIOS_DIR
from core.artifacts import _build_timestamp
from packs.paths import MEDIA_MARKER, _has_path_conflict
from core.artifacts import build_timestamp
from packs.paths import MEDIA_MARKER, has_path_conflict
from core.ziptools import build_zip_contents_index
from core.ziptools import check_inside_zip
from resolve.nativemode import digest_algorithm
@@ -28,7 +28,7 @@ from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
import os
from packs.extras import platform_region_groups
from packs.paths import _flat
from packs.paths import flat_arcname
from resolve.nativemode import reads_file_contents
from resolve import regions as resolve_regions
from packs import slots
@@ -237,7 +237,7 @@ def verify_pack(
"schema_version": 1,
"version": 1,
"generator": "retrobios generate_pack.py",
"generated": _build_timestamp(db),
"generated": build_timestamp(db),
"files": [],
}
errors: list[str] = []
@@ -595,7 +595,7 @@ def _builder_extras(
there: taken by the refused file, that core file was never compared.
"""
from packs.extras import ExtraResolver, hidden_extras
from resolve.validation import _build_validation_index, destination_owners
from resolve.validation import build_validation_index, destination_owners
config, emu_profiles = expect.config, expect.emu_profiles
data_registry = expect.opts.data_registry
@@ -632,7 +632,7 @@ def _builder_extras(
expect.region_drops or None,
resolver=ExtraResolver(
db, DEFAULT_BIOS_DIR, build_zip_contents_index(db), data_registry,
_build_validation_index(platform_profiles),
build_validation_index(platform_profiles),
destination_owners(platform_profiles), True, profiles=emu_profiles,
),
placed_local=placed_local,
@@ -855,7 +855,7 @@ def _count_baseline(
member = expected
elif expected.lower() in view.zip_lower:
member = view.zip_lower[expected.lower()]
elif _has_path_conflict(expected, view.zip_set, view.zip_parents):
elif has_path_conflict(expected, view.zip_set, view.zip_parents):
# Skipped by the builder for the same reason: not an error
count.present += 1
continue
@@ -967,7 +967,7 @@ def _check_core_extras(
)
for full, local in sorted(placed_local.items()):
core_checked += 1
flat = _flat(full, expect.base_dest, view.is_flat)
flat = flat_arcname(full, expect.base_dest, view.is_flat)
member = flat if flat in view.zip_set else view.zip_lower.get(flat.lower())
if member is None:
errors.append(f"core missing: {full}")
+43 -43
View File
@@ -9,7 +9,7 @@ from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from core.artifacts import _build_timestamp
from core.artifacts import build_timestamp
from core.options import reject_unknown
from core.paths import REPO_ROOT, declared_destination, sanitize_pack_path
from model.declarations import OUTER_ROOTS, declared_root, outer_layout
@@ -19,50 +19,50 @@ from model.registry import load_data_dir_registry
from model.safeparse import yaml_load
from model.systems import platform_system_names
from packs import slots
from packs.archive import CASE_FOLDING_OS, PACK_DOCUMENTS, _Placed
from packs.archive import CASE_FOLDING_OS, PACK_DOCUMENTS, Placed
from packs.datatrees import (
_data_directory_members,
_in_data_cache,
_manifest_data_directories,
data_directory_members,
in_data_cache,
manifest_data_directories,
core_data_trees,
pack_markers,
tree_readers,
)
from packs.extras import (
_collect_emulator_extras,
collect_emulator_extras,
extra_region_key,
save_entry_fields,
save_manifest_dest,
undeclared_report,
)
from packs.manifestcores import (
_downloaded_cores,
_manifest_core_entries,
_manifest_core_index,
_manifest_selection,
_offered_boards,
downloaded_cores,
manifest_core_entries,
manifest_core_index,
manifest_selection,
offered_boards,
)
from packs.manifestentry import (
MANIFEST_OUTER_FIELDS,
_ClaimContext,
_attach_claims,
_manifest_dest_of,
_manifest_entry,
_record_absent,
_record_slot_choices,
_record_unplaceable,
ClaimContext,
attach_claims,
manifest_dest_of,
manifest_entry,
record_absent,
record_slot_choices,
record_unplaceable,
)
from packs.manifestselect import SelectionIndex
from packs.paths import save_layout
from packs.scope import platform_list_version, system_titles
from packs.standalone import _standalone_copies, _standalone_layouts
from packs.standalone import standalone_copies, standalone_layouts
from resolve.contentlayout import TARGET_KEY
from resolve.cores import filter_systems_by_target, resolve_platform_cores as _platform_cores
from resolve.gamedata import GAME_DATA, is_game_data, platform_game_data, without_game_data
from resolve.nativemode import digest_algorithm, reads_file_contents
from resolve.packfiles import preferred_entries as _preferred_entries, resolve_declaration
from resolve.validation import (
_build_validation_index,
build_validation_index,
agnostic_substitute,
baseline_verdict,
destination_owners,
@@ -148,7 +148,7 @@ class _ManifestBuild:
manifest_validation: dict = field(default_factory=dict)
manifest_owners: dict = field(default_factory=dict)
game_destinations: set[str] = field(default_factory=set)
placed: _Placed = field(init=False)
placed: Placed = field(init=False)
# Destination -> (entry, full destination, manifest destination) of each
# platform file, for the core claims a target build would fall back on.
platform_entries: dict[str, tuple[dict, str, str]] = field(default_factory=dict)
@@ -177,7 +177,7 @@ class _ManifestBuild:
data_directories: list[dict] = field(default_factory=list)
def __post_init__(self) -> None:
self.placed = _Placed(self.case_insensitive)
self.placed = Placed(self.case_insensitive)
@property
def base_dest(self) -> str:
@@ -197,7 +197,7 @@ class _ManifestBuild:
return self.selection
def manifest_destination(self, full_destination: str) -> str:
return _manifest_dest_of(full_destination, self.base_dest)
return manifest_dest_of(full_destination, self.base_dest)
def record_omission(
self,
@@ -355,7 +355,7 @@ class _ManifestBuild:
local_path: str,
settle: _Settle,
) -> None:
entry, file_size = _manifest_entry(
entry, file_size = manifest_entry(
local_path, dest, None, self.db, self.repo_root,
self.fields.fields(dest, file_entry["name"]),
)
@@ -364,14 +364,14 @@ class _ManifestBuild:
if entry is not None and self.opts.target_cores is None:
order = self.declaration_order(full_dest)
if full_dest in self.slot_choices or len(order) > 1:
_record_slot_choices(
record_slot_choices(
entry, self.slot_choices.get(full_dest, []), order,
settle, dest, self.db, self.repo_root,
)
if entry is None:
self.record_omission(full_dest, file_entry, sys_id, "not_found", None)
if file_size and full_dest not in self.placed.destinations:
if _in_data_cache(local_path, self.data_registry):
if in_data_cache(local_path, self.data_registry):
self.cache_held[full_dest] = (local_path, file_size)
else:
self.pack_only_sizes.append(file_size)
@@ -384,8 +384,8 @@ class _ManifestBuild:
self.total_size += file_size
self.placed.take(full_dest)
def claim_context(self) -> _ClaimContext:
return _ClaimContext(
def claim_context(self) -> ClaimContext:
return ClaimContext(
self.db, self.bios_dir, self.zip_contents, self.opts.offline,
self.opts.required_only, self.manifest_validation, self.manifest_owners,
self.repo_root, self.data_registry,
@@ -398,7 +398,7 @@ class _ManifestBuild:
baseline_claims: dict[str, dict] = {}
absent: list[dict] = []
if opts.source != "platform":
core_files = _collect_emulator_extras(
core_files = collect_emulator_extras(
self.config,
opts.emulators_dir,
self.db,
@@ -414,12 +414,12 @@ class _ManifestBuild:
)
else:
core_files = []
_record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles)
_record_absent(
record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles)
record_absent(
absent, self.config, self.base_dest, self.region_drops, opts.required_only,
self.placed.destinations, self.omitted_by_destination, self.record_omission,
)
self.total_size += _manifest_core_entries(
self.total_size += manifest_core_entries(
core_files, self.config, self.db, self.bios_dir, self.base_dest, self.repo_root,
self.zip_contents, opts.offline,
region_drops=self.region_drops, case_insensitive=self.case_insensitive,
@@ -445,7 +445,7 @@ class _ManifestBuild:
# still fills it.
entry.pop("category", None)
if claims:
_attach_claims(entry, claims, ctx, dest, dest)
attach_claims(entry, claims, ctx, dest, dest)
# A platform omission narrows like a platform file: by the systems
# declaring it, which can be fewer than the ones whose cores read it.
for full_dest, omission in self.omitted_by_destination.items():
@@ -471,7 +471,7 @@ class _ManifestBuild:
core_trees = ([] if opts.source == "platform"
else core_data_trees(self.config, self.emu_profiles, self.platform_name,
self.data_registry, opts.target_cores))
self.data_members = list(_data_directory_members(
self.data_members = list(data_directory_members(
self.pack_systems, self.data_registry, self.platform_name, self.base_dest,
self.case_insensitive, self.placed.destinations, self.placed.lower,
self.placed.parents, refs_out=data_refs, required_only=required_only,
@@ -486,7 +486,7 @@ class _ManifestBuild:
self.pack_only_sizes.append(size)
else:
self.omitted_by_destination.pop(full_dest, None)
self.data_directories = _manifest_data_directories(
self.data_directories = manifest_data_directories(
self.data_members, data_refs, self.data_registry or {}, self.base_dest,
tree_readers(self.pack_systems, core_trees), self.pack_systems,
)
@@ -499,7 +499,7 @@ class _ManifestBuild:
# The pack is unzipped into the BIOS folder: an entry the installer puts
# in the roms, emulators or configs folder is in its list, not in the ZIP.
outer = [e for e in manifest_files if e.get("root") in OUTER_ROOTS]
core_names, system_cores = _manifest_core_index(
core_names, system_cores = manifest_core_index(
config, self.emu_profiles, manifest_files, list(omitted.values())
)
result: dict = {
@@ -521,10 +521,10 @@ class _ManifestBuild:
"platform": platform_name,
"display_name": config.get("platform", platform_name),
"version": platform_list_version(config, platform_name),
"generated": _build_timestamp(self.db),
"generated": build_timestamp(self.db),
"base_destination": self.base_dest,
"detect": self.install_section.get("detect", []),
"standalone_copies": _standalone_copies(
"standalone_copies": standalone_copies(
self.install_section.get("standalone_copies", []), self.manifest_profiles,
manifest_files,
),
@@ -542,10 +542,10 @@ class _ManifestBuild:
omitted.values(), key=lambda entry: entry["dest"]
),
"core_names": core_names,
**({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores(
**({"downloaded_cores": downloaded} if (downloaded := downloaded_cores(
config, self.emu_profiles, core_names, self.platforms_dir,
)) else {}),
**({"offered_boards": offered} if (offered := _offered_boards(
**({"offered_boards": offered} if (offered := offered_boards(
config, self.emu_profiles, core_names,
[*manifest_files, *omitted.values()],
)) else {}),
@@ -634,7 +634,7 @@ def _start_manifest(
name: emu_profiles[name]
for name in _platform_cores(config, emu_profiles)
}
build.manifest_validation = _build_validation_index(build.manifest_profiles)
build.manifest_validation = build_validation_index(build.manifest_profiles)
build.manifest_owners = destination_owners(build.manifest_profiles)
_settle_manifest_scope(build)
return build, full_profiles
@@ -679,7 +679,7 @@ def _settle_manifest_scope(build: _ManifestBuild) -> None:
if opts.source != "platform"
else None
)
build.region_drops, build.selection, build.builder_held = _manifest_selection(
build.region_drops, build.selection, build.builder_held = manifest_selection(
config, build.pack_systems, opts.emulators_dir, build.db, build.base_dest,
emu_profiles, opts.target_cores, opts.source,
required_only=opts.required_only, regions=opts.regions,
@@ -822,7 +822,7 @@ def generate_install_list(
**truth_options, known_slot_choices=built["slot_choices"],
)
_mark_truth(result, truth)
layouts = _standalone_layouts(
layouts = standalone_layouts(
built["profiles"], settings.emulators_dir, db, bios_dir,
settings.zip_contents or {}, settings.offline, platforms_dir, result,
)
+37 -37
View File
@@ -14,8 +14,8 @@ from model.profiles import upstream_profile_index
from model.targets import list_available_targets, load_target_config
from packs.extras import (
ExtraResolver,
_detect_extras_prefix,
_extra_system_ids,
detect_extras_prefix,
extra_system_ids,
extra_full_destination,
extra_region_key,
platform_region_groups,
@@ -23,18 +23,18 @@ from packs.extras import (
save_manifest_dest,
)
from packs.manifestentry import (
_ClaimContext,
_attach_claims,
_claim_cores,
_claim_platform_omission,
_manifest_dest_of,
_manifest_entry,
ClaimContext,
attach_claims,
claim_cores,
claim_platform_omission,
manifest_dest_of,
manifest_entry,
)
from packs.manifestselect import SelectionIndex
from packs.paths import _register_path, placement_block
from packs.platformpack import _slot_drops
from packs.paths import register_path, placement_block
from packs.platformpack import one_per_slot_drops
from resolve import regions as resolve_regions, slot as slot_mod
from resolve.contentlayout import TARGET_KEY, _core_key, content_folder_boards
from resolve.contentlayout import TARGET_KEY, core_key, content_folder_boards
from resolve.cores import (
downloadable_on,
downloaded_only_profiles,
@@ -48,7 +48,7 @@ if TYPE_CHECKING:
class _CoreEntryState(TypedDict):
"""What _manifest_core_entries reads and fills of the manifest being listed."""
"""What manifest_core_entries reads and fills of the manifest being listed."""
region_drops: set
case_insensitive: bool
@@ -63,7 +63,7 @@ class _CoreEntryState(TypedDict):
class _CoreEntryParts(_CoreEntryState, total=False):
"""_CoreEntryState and the optional keywords of _manifest_core_entries."""
"""_CoreEntryState and the optional keywords of manifest_core_entries."""
required_only: bool
validation_index: dict | None
@@ -78,14 +78,14 @@ class _CoreEntryLister:
config: dict
base_dest: str
ctx: _ClaimContext
ctx: ClaimContext
state: _CoreEntryParts
resolver: ExtraResolver
total_size: int = 0
extras_pfx: str = field(init=False)
def __post_init__(self) -> None:
self.extras_pfx = _detect_extras_prefix(self.config, self.base_dest)
self.extras_pfx = detect_extras_prefix(self.config, self.base_dest)
def region_key(self, fe: dict) -> str:
return extra_region_key(fe, declared_root(self.config))
@@ -139,7 +139,7 @@ class _CoreEntryLister:
save_root = fe.get("root") == "save"
folded = (
save_manifest_dest(fe) if save_root
else _manifest_dest_of(full_dest, self.base_dest)
else manifest_dest_of(full_dest, self.base_dest)
).lower()
held = next(
(e for e in self.state["manifest_files"]
@@ -148,16 +148,16 @@ class _CoreEntryLister:
None,
)
if held is not None and held.get("cores") is not None:
_attach_claims(held, [fe], self.ctx, dest, held["dest"])
attach_claims(held, [fe], self.ctx, dest, held["dest"])
def _omit(self, fe: dict, full_dest: str, reason: str) -> None:
source_emu = fe.get("source_profile") or fe.get("source_emulator", "")
if not _claim_platform_omission(
if not claim_platform_omission(
self.state["omitted_by_destination"].get(full_dest), source_emu
):
systems = _extra_system_ids(fe)
systems = extra_system_ids(fe)
self.state["record_omission"](
full_dest, fe, systems[0] if systems else "", reason, _claim_cores(fe),
full_dest, fe, systems[0] if systems else "", reason, claim_cores(fe),
)
def _list_held(
@@ -178,9 +178,9 @@ class _CoreEntryLister:
# Relative to the roms or emulators folder the entry names.
manifest_dest = dest
else:
manifest_dest = _manifest_dest_of(full_dest, self.base_dest)
manifest_dest = manifest_dest_of(full_dest, self.base_dest)
entry, file_size = _manifest_entry(
entry, file_size = manifest_entry(
local_path, manifest_dest, [source_emu] if source_emu else [],
self.ctx.db, self.ctx.repo_root,
state["selection"].fields(region_key, fe.get("name", "")),
@@ -199,7 +199,7 @@ class _CoreEntryLister:
is_game_data(claim) for claim in fe.get("other_claims", [])
):
entry["category"] = GAME_DATA
_attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest)
attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest)
state["manifest_files"].append(entry)
displaced = state["omitted_by_destination"].pop(full_dest, None)
@@ -212,12 +212,12 @@ class _CoreEntryLister:
)
self.total_size += file_size
state["seen_destinations"].add(full_dest)
_register_path(full_dest, state["seen_destinations"], state["seen_parents"])
register_path(full_dest, state["seen_destinations"], state["seen_parents"])
if state["case_insensitive"]:
state["seen_lower"].add(full_dest.lower())
def _manifest_core_entries(
def manifest_core_entries(
core_files: list,
config: dict,
db: dict,
@@ -236,11 +236,11 @@ def _manifest_core_entries(
Returns the bytes added.
"""
reject_unknown(
"_manifest_core_entries", state,
"manifest_core_entries", state,
_CoreEntryParts.__required_keys__ | _CoreEntryParts.__optional_keys__,
)
required_only = state.get("required_only", False)
ctx = _ClaimContext(
ctx = ClaimContext(
db, bios_dir, zip_contents, offline, required_only,
state.get("validation_index"), state.get("owners"), repo_root,
state.get("data_registry"),
@@ -261,7 +261,7 @@ def _manifest_core_entries(
class _SelectionOptions(TypedDict, total=False):
"""The keyword options of _manifest_selection."""
"""The keyword options of manifest_selection."""
required_only: bool
regions: list[str] | None
@@ -272,7 +272,7 @@ class _SelectionOptions(TypedDict, total=False):
one_per_slot: bool
def _manifest_selection(
def manifest_selection(
config: dict,
pack_systems: dict,
emulators_dir: str,
@@ -290,7 +290,7 @@ def _manifest_selection(
decides on the full manifest withdraws what `--region` and
`--one-per-slot` withdraw from the pack.
"""
reject_unknown("_manifest_selection", options, _SelectionOptions.__optional_keys__)
reject_unknown("manifest_selection", options, _SelectionOptions.__optional_keys__)
required_only = options.get("required_only", False)
regions = options.get("regions")
one_per_slot = options.get("one_per_slot", False)
@@ -323,7 +323,7 @@ def _manifest_selection(
else set()
)
if one_per_slot:
drops = drops | _slot_drops(
drops = drops | one_per_slot_drops(
config, emu_profiles, target_cores, region_groups, drops, held
)[0]
return drops, SelectionIndex.build(
@@ -333,7 +333,7 @@ def _manifest_selection(
), held
def _offered_boards(
def offered_boards(
config: dict,
profiles: dict[str, dict],
core_names: dict[str, list[str]],
@@ -354,18 +354,18 @@ def _offered_boards(
pairs = content_folder_boards(config)
if all(on is None for on in pairs.values()):
return {}
from resolve.launchers import _roms_place
from resolve.launchers import roms_place_of
by_key: dict[str, set[str]] = {}
for name, claimants in upstream_profile_index(profiles).items():
by_key.setdefault(_core_key(name), set()).update(claimants)
by_key.setdefault(core_key(name), set()).update(claimants)
free = {
(profile, folder) for (core, folder), on in pairs.items() if on is None
for profile in by_key.get(core, ())
}
found: dict[tuple[str, str, str], set[str]] = {}
for (core, folder), on in pairs.items():
where = _roms_place(config, folder) if on is not None else None
where = roms_place_of(config, folder) if on is not None else None
if where is None:
continue
for profile in by_key.get(core, ()):
@@ -392,7 +392,7 @@ def _offered_boards(
return result
def _downloaded_cores(
def downloaded_cores(
config: dict,
profiles: dict[str, dict],
core_names: dict[str, list[str]],
@@ -425,7 +425,7 @@ def _downloaded_cores(
return {profile: sorted(names) for profile, names in sorted(boards.items())}
def _manifest_core_index(
def manifest_core_index(
config: dict,
profiles: dict[str, dict],
files: list[dict],
+17 -17
View File
@@ -12,8 +12,8 @@ from core.paths import declared_destination
from model.declarations import OUTER_ROOTS, declared_root
from model.largefiles import asset_name, load_registered_paths, published_asset_name
from packs.extras import (
_detect_extras_prefix,
_extra_system_ids,
detect_extras_prefix,
extra_system_ids,
extra_full_destination,
extra_region_key,
save_manifest_dest,
@@ -124,7 +124,7 @@ def _stable_hashes(local_path: str, db: dict) -> dict:
)
def _manifest_entry(
def manifest_entry(
local_path: str | None,
dest: str,
cores: list[str] | None,
@@ -192,7 +192,7 @@ def _is_program(path: str) -> bool:
@dataclass(frozen=True)
class _ClaimContext:
class ClaimContext:
"""How a manifest resolves and judges the copy a core claim names."""
db: dict
@@ -206,10 +206,10 @@ class _ClaimContext:
data_registry: dict | None = None
def _attach_claims(
def attach_claims(
entry: dict,
claims: list[dict],
ctx: _ClaimContext,
ctx: ClaimContext,
dest: str,
manifest_dest: str,
) -> None:
@@ -248,7 +248,7 @@ def _attach_claims(
claim, claim_path, ctx.db, ctx.validation_index or {}, ctx.bios_dir, None,
claim.get("layout_path") or dest, ctx.owners,
)
copy, _size = _manifest_entry(
copy, _size = manifest_entry(
claim_path, manifest_dest, [claim_emu], ctx.db, ctx.repo_root, {}
)
if copy is None:
@@ -267,7 +267,7 @@ def _attach_claims(
def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict:
"""The omission a claim with nothing held stands for."""
systems = _extra_system_ids(claim)
systems = extra_system_ids(claim)
return {
"name": str(claim.get("name") or ""),
"system": systems[0] if systems else "",
@@ -281,7 +281,7 @@ def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict:
}
def _record_slot_choices(
def record_slot_choices(
entry: dict,
choices: list[tuple[str, str | None]],
declarations: list[tuple[list[str], dict, str]],
@@ -303,7 +303,7 @@ def _record_slot_choices(
local_path, _status = settle(file_entry, sys_id, dest, override)
if local_path is None:
return None
copy, _size = _manifest_entry(local_path, dest, None, db, repo_root, {})
copy, _size = manifest_entry(local_path, dest, None, db, repo_root, {})
if copy is None:
return None
return {k: v for k, v in copy.items() if k not in ("dest", "cores")}
@@ -341,14 +341,14 @@ def _record_slot_choices(
entry["declared_choices"] = declared
def _manifest_dest_of(full_dest: str, base_dest: str) -> str:
def manifest_dest_of(full_dest: str, base_dest: str) -> str:
"""A pack destination as the manifest writes it, below base_destination."""
if base_dest and full_dest.startswith(f"{base_dest}/"):
return full_dest[len(base_dest) + 1:]
return full_dest
def _claim_platform_omission(held: dict | None, emulator: str) -> bool:
def claim_platform_omission(held: dict | None, emulator: str) -> bool:
"""Record a core's claim on a destination the platform already omits.
The platform's own omission stands while one of its declaring systems
@@ -365,7 +365,7 @@ def _claim_platform_omission(held: dict | None, emulator: str) -> bool:
return True
def _claim_cores(fe: dict) -> list[str]:
def claim_cores(fe: dict) -> list[str]:
"""The cores an extra and the claims folded onto it name: an omission
names every core reading the file, as a list built for one of them
would."""
@@ -376,7 +376,7 @@ def _claim_cores(fe: dict) -> list[str]:
return sorted(name for name in names if name)
def _record_absent(
def record_absent(
absent: list[dict],
config: dict,
base_dest: str,
@@ -392,7 +392,7 @@ def _record_absent(
pak000-004 reached no safety notice: the installer said everything
was verified and the game refused to start.
"""
extras_pfx = _detect_extras_prefix(config, base_dest)
extras_pfx = detect_extras_prefix(config, base_dest)
for fe in absent:
if required_only and fe.get("required") is False:
continue
@@ -414,7 +414,7 @@ def _record_absent(
and source_emu not in claimed):
held["cores"] = sorted([*claimed, source_emu])
continue
systems = _extra_system_ids(fe)
systems = extra_system_ids(fe)
record_omission(
full_dest, fe, systems[0] if systems else "", "not_found",
[source_emu] if source_emu else [],
@@ -429,7 +429,7 @@ def _record_absent(
MANIFEST_OUTER_FIELDS = ("bios_folder", "from_bios", "searched", "default", "config")
def _record_unplaceable(
def record_unplaceable(
unplaceable: list[dict],
record_omission: Callable[..., None],
config: dict,
+7 -7
View File
@@ -19,11 +19,11 @@ from dataclasses import dataclass
from resolve import regions as resolve_regions
from resolve import slot as slot_mod
from model.systems import _norm_system_id
from model.systems import norm_system_id
from core.paths import declared_destination
from packs.extras import (
_kept,
_serving_system_ids,
kept_entries,
serving_system_ids,
extra_region_groups,
extra_region_key,
system_spellings,
@@ -54,11 +54,11 @@ class SelectionIndex:
) -> SelectionIndex:
by_norm: dict[str, set[str]] = {}
for sys_id in pack_systems:
by_norm.setdefault(_norm_system_id(sys_id), set()).add(sys_id)
by_norm.setdefault(norm_system_id(sys_id), set()).add(sys_id)
declared_by: dict[str, set[str]] = {}
for sys_id, system in pack_systems.items():
for file_entry in _kept(system.get("files", []), required_only):
for file_entry in kept_entries(system.get("files", []), required_only):
dest = declared_destination(file_entry)
if dest:
declared_by.setdefault(dest, set()).add(sys_id)
@@ -76,9 +76,9 @@ class SelectionIndex:
)
# A profile system the platform does not have is no system the
# pack's --system accepts: it would offer what the pack refuses.
for sys_id in _serving_system_ids(extra):
for sys_id in serving_system_ids(extra):
owned_by.setdefault(dest, set()).update(
by_norm.get(_norm_system_id(sys_id), ())
by_norm.get(norm_system_id(sys_id), ())
)
systems_by_dest = {
+8 -8
View File
@@ -11,9 +11,9 @@ from typing import TYPE_CHECKING, TypedDict
from core.options import reject_unknown
from model.platforms import load_platform_config
from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles
from packs.archive import _add_pack_member, _writing_pack
from packs.naming import _name_part, _narrowings
from packs.paths import _resolve_destination
from packs.archive import add_pack_member, writing_pack
from packs.naming import file_name_part, pack_narrowings
from packs.paths import resolve_destination
from resolve.packfiles import resolve_file, sha1_for_hash
if TYPE_CHECKING:
@@ -134,7 +134,7 @@ def _md5_pack_name(
# take the name of a run without it.
custom_tags = "".join(
tag
for tag, _label in _narrowings(
for tag, _label in pack_narrowings(
"full", None, None, False, False, standalone=opts.standalone
)
)
@@ -144,7 +144,7 @@ def _md5_pack_name(
"\n".join(sorted(f"{kind}:{value.lower()}" for kind, value in hashes)).encode()
).hexdigest()[:8]
return (
f"{_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}"
f"{file_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}"
"_BIOS_Pack.zip"
)
@@ -166,7 +166,7 @@ def _md5_destination(entry: dict, layout: _Md5Layout, opts: _Md5Settings) -> str
if opts.emulator_name:
# Laid out as the emulator pack lays it out: its path and
# its standalone_path, which --standalone has to reach.
dest = _resolve_destination(matched_fe, opts.standalone)
dest = resolve_destination(matched_fe, opts.standalone)
else:
dest = matched_fe.get("destination", matched_fe.get("name", name))
elif paths:
@@ -202,7 +202,7 @@ def generate_md5_pack(
not_in_db: list[str] = []
seen: set[str] = set()
with _writing_pack(zip_path) as zf:
with writing_pack(zip_path) as zf:
for hash_type, hash_val in hashes:
sha1 = sha1_for_hash(hash_type, hash_val, db)
if not sha1:
@@ -225,7 +225,7 @@ def generate_md5_pack(
not_in_repo.append((name, hash_val))
continue
_add_pack_member(zf, local_path, full_dest)
add_pack_member(zf, local_path, full_dest)
packed.append((name, hash_val))
total = len(hashes)
+25 -25
View File
@@ -15,7 +15,7 @@ from packs import parts as packs_parts
from resolve.grouping import group_identical_platforms
def _narrowings(
def pack_narrowings(
source: str,
regions: list[str] | None,
target_name: str | None,
@@ -69,7 +69,7 @@ def _target_tag(target_name: str) -> str:
)
def _platform_target(
def platform_target(
platform_name: str, target: str | None, platforms_dir: str
) -> str | None:
"""The target as this platform files it, the name its artifacts carry.
@@ -86,7 +86,7 @@ def _platform_target(
return canonical_target_name([platform_name], target, platforms_dir)
def _system_tag(system_filter: list[str] | None) -> str:
def system_tag(system_filter: list[str] | None) -> str:
"""Filename tag for a pack limited to some systems, empty for all."""
if not system_filter:
return ""
@@ -98,7 +98,7 @@ def _system_tag(system_filter: list[str] | None) -> str:
s = s[len(prefix) :]
break
display_parts.append("_".join(p.title() for p in s.split("-") if p))
return "_" + _bounded_join(display_parts, system_filter)
return "_" + bounded_join(display_parts, system_filter)
# A system list long enough to push a pack name past this falls back to the
@@ -106,7 +106,7 @@ def _system_tag(system_filter: list[str] | None) -> str:
MAX_SYSTEM_TAG_BYTES = 120
def _bounded_join(parts: list[str], keys: list[str]) -> str:
def bounded_join(parts: list[str], keys: list[str]) -> str:
"""Parts joined while they fit, else the first, a count and a digest.
Thirty systems joined made a 261-byte file name and the ZIP could not
@@ -125,7 +125,7 @@ def _bounded_join(parts: list[str], keys: list[str]) -> str:
_UNSAFE_IN_NAME = re.compile(r'[/\\:*?"<>|]')
def _name_part(text: str, space: str = "") -> str:
def file_name_part(text: str, space: str = "") -> str:
"""A display name made safe to stand in a file name.
'FinalBurn Neo (CPS-1/CPS-2)' named a directory that did not exist, and a
@@ -134,7 +134,7 @@ def _name_part(text: str, space: str = "") -> str:
return _UNSAFE_IN_NAME.sub("-", text.replace(" ", space))
def _platform_pack_stem(
def platform_pack_stem(
group_platforms: list[str], representative: str, platforms_dir: str
) -> str:
"""Platform part of a pack name, version included.
@@ -144,7 +144,7 @@ def _platform_pack_stem(
"""
rep_cfg = load_platform_config(representative, platforms_dir)
version = rep_cfg.get("version", rep_cfg.get("dat_version", ""))
version_tag = f"_{_name_part(str(version))}" if version else ""
version_tag = f"_{file_name_part(str(version))}" if version else ""
return platform_pack_prefix(group_platforms, representative, platforms_dir) + version_tag
@@ -158,15 +158,15 @@ def platform_pack_prefix(
"""
if len(group_platforms) <= 1:
rep_cfg = load_platform_config(representative, platforms_dir)
return _name_part(rep_cfg.get("platform", representative), "_")
return file_name_part(rep_cfg.get("platform", representative), "_")
names = [
load_platform_config(p, platforms_dir).get("platform", p)
for p in group_platforms
]
return "_".join(_name_part(n) for n in names)
return "_".join(file_name_part(n) for n in names)
def _platform_pack_name(
def platform_pack_name(
platform_name: str,
platforms_dir: str,
narrowings: list[tuple[str, str]],
@@ -179,9 +179,9 @@ def _platform_pack_name(
"""
if pack_name:
return pack_name
stem = _platform_pack_stem([platform_name], platform_name, platforms_dir)
stem = platform_pack_stem([platform_name], platform_name, platforms_dir)
tags = "".join(tag for tag, _label in narrowings)
return f"{stem}{tags}_BIOS_Pack{_system_tag(system_filter)}.zip"
return f"{stem}{tags}_BIOS_Pack{system_tag(system_filter)}.zip"
# A file name holds 255 bytes on every filesystem a pack is written to,
@@ -189,7 +189,7 @@ def _platform_pack_name(
MAX_PACK_NAME_BYTES = 200
def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -> str:
def bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -> str:
"""The emulator pack's file name, its emulators joined while they fit.
Past the limit the name keeps the first emulator, says how many more the
@@ -203,7 +203,7 @@ def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -
return f"{display_names[0]}_and_{len(display_names) - 1}_more_{digest}{suffix}"
def _expected_pack_names(
def expected_pack_names(
platforms: list[str],
platforms_dir: str,
regions: list[str] | None,
@@ -220,11 +220,11 @@ def _expected_pack_names(
the (source, required_only) combinations the run built.
"""
def narrow_tags(platform_name: str) -> list[str]:
named = _platform_target(platform_name, target_name, platforms_dir)
named = platform_target(platform_name, target_name, platforms_dir)
return [
"".join(
tag
for tag, _label in _narrowings(
for tag, _label in pack_narrowings(
source, regions, named, False, required, no_game_data=no_game_data
)
)
@@ -233,7 +233,7 @@ def _expected_pack_names(
names: dict[str, set[str]] = {
p: {
f"{_platform_pack_stem([p], p, platforms_dir)}{tags}_BIOS_Pack.zip"
f"{platform_pack_stem([p], p, platforms_dir)}{tags}_BIOS_Pack.zip"
for tags in narrow_tags(p)
}
for p in platforms
@@ -255,7 +255,7 @@ def _expected_pack_names(
):
if len(group) < 2:
continue
stem = _platform_pack_stem(group, representative, platforms_dir)
stem = platform_pack_stem(group, representative, platforms_dir)
for tags in narrow_tags(representative):
for p in group:
if p in names:
@@ -281,7 +281,7 @@ def _content_narrowing_tags() -> tuple[str, ...]:
for source, one_per_slot, required_only in dimensions:
tags.extend(
tag
for tag, _label in _narrowings(source, None, None, one_per_slot, required_only)
for tag, _label in pack_narrowings(source, None, None, one_per_slot, required_only)
)
return tuple(tags)
@@ -289,7 +289,7 @@ def _content_narrowing_tags() -> tuple[str, ...]:
_CONTENT_NARROWING_TAGS = _content_narrowing_tags()
def _narrows_contents(pack_name: str) -> bool:
def narrows_contents(pack_name: str) -> bool:
"""True when a pack holds fewer files than the platform declares.
A source-restricted or required-only build is narrower by design, so the
@@ -300,15 +300,15 @@ def _narrows_contents(pack_name: str) -> bool:
return any(f"{tag}_" in pack_name for tag in _CONTENT_NARROWING_TAGS)
def _pack_variant(pack_name: str) -> tuple[str, bool] | None:
def pack_variant(pack_name: str) -> tuple[str, bool] | None:
"""The (source, required_only) a pack was built as, read from its name.
None for a one-per-slot pack, whose slot choice the check does not
replay. The tags come from the name builder, as for _narrows_contents.
replay. The tags come from the name builder, as for narrows_contents.
"""
def tagged(**dimension: object) -> bool:
tags = [
tag for tag, _label in _narrowings(
tag for tag, _label in pack_narrowings(
str(dimension.get("source", "full")), None, None,
bool(dimension.get("one_per_slot", False)),
bool(dimension.get("required_only", False)),
@@ -324,7 +324,7 @@ def _pack_variant(pack_name: str) -> tuple[str, bool] | None:
return source, tagged(required_only=True)
def _pack_archives(output_dir: str) -> list[str]:
def pack_archives(output_dir: str) -> list[str]:
"""The ZIPs of a directory that are packs.
A part of a split pack holds a share of a platform by design and was
+6 -6
View File
@@ -151,7 +151,7 @@ def _path_parents(dest: str) -> list[str]:
parts = dest.split("/")
return ["/".join(parts[:i]) for i in range(1, len(parts))]
def _has_path_conflict(dest: str, seen_files: set[str], seen_parents: set[str]) -> bool:
def has_path_conflict(dest: str, seen_files: set[str], seen_parents: set[str]) -> bool:
"""Check if dest conflicts with existing paths (file vs directory).
Returns True if adding dest would create an impossible extraction:
@@ -179,12 +179,12 @@ def placement_block(
return "taken"
if case_insensitive and dest.lower() in seen_lower:
return "case_twin"
if _has_path_conflict(dest, seen_files, seen_parents):
if has_path_conflict(dest, seen_files, seen_parents):
return "path_conflict"
return None
def _register_path(dest: str, seen_files: set[str], seen_parents: set[str]) -> None:
def register_path(dest: str, seen_files: set[str], seen_parents: set[str]) -> None:
"""Track a file path and its parent directories."""
seen_files.add(dest)
for parent in _path_parents(dest):
@@ -207,13 +207,13 @@ def lands_on_android(target_names: Iterable[str], target: str | None) -> bool:
return any(name.startswith("android") for name in target_names)
def _flat(arcname: str, prefix: str, flatten: bool) -> str:
def flat_arcname(arcname: str, prefix: str, flatten: bool) -> str:
"""Strip base_destination prefix from ZIP arcname when flattening."""
if flatten and prefix and arcname.startswith(prefix + "/"):
return arcname[len(prefix) + 1:]
return arcname
def _resolve_destination(file_entry: dict, standalone: bool) -> str:
def resolve_destination(file_entry: dict, standalone: bool) -> str:
"""Resolve the ZIP destination path for a file entry.
``path:`` is where the libretro build reads the file from the system
@@ -241,7 +241,7 @@ def _resolve_destination(file_entry: dict, standalone: bool) -> str:
return dest
def _archive_destination(
def archive_destination(
archive_name: str, archive_prefix: str, pack_structure: dict | None, standalone: bool
) -> str:
"""Where an emulator pack places one of the profile's archives."""
+55 -55
View File
@@ -24,29 +24,29 @@ from packs import slots
from packs.archive import (
CASE_FOLDING_OS,
PackRecord,
_Placed,
_add_pack_member,
_add_zip_to_pack,
_extract_zip_to_archive,
_same_bytes,
_write_generated_member,
_writing_pack,
Placed,
add_pack_member,
add_zip_to_pack,
extract_zip_to_archive,
same_bytes,
write_generated_member,
writing_pack,
)
from packs.datatrees import _data_directory_members, core_data_trees, pack_markers
from packs.emulatorpack import _system_display_name
from packs.datatrees import data_directory_members, core_data_trees, pack_markers
from packs.emulatorpack import system_display_name
from packs.extras import (
ExtraResolver,
_collect_emulator_extras,
_detect_extras_prefix,
collect_emulator_extras,
detect_extras_prefix,
extra_full_destination,
extra_region_key,
extras_for_systems as _extras_for_systems,
platform_region_groups,
undeclared_report,
)
from packs.naming import _name_part, _narrowings, _platform_pack_name, _platform_pack_stem
from packs.paths import _flat, save_layout
from packs.readme import _build_agnostic_rename_readme, _build_readme, save_place
from packs.naming import file_name_part, pack_narrowings, platform_pack_name, platform_pack_stem
from packs.paths import flat_arcname, save_layout
from packs.readme import build_agnostic_rename_readme, build_readme, save_place
from resolve import packfiles as packresolve, regions as resolve_regions, slot as slot_mod
from resolve.contentlayout import TARGET_KEY
from resolve.cores import platform_scope_systems, system_scope_error
@@ -59,8 +59,8 @@ from resolve.packfiles import (
resolve_file,
)
from resolve.validation import (
_build_validation_index,
_parse_validation,
build_validation_index,
parse_validation,
agnostic_substitute,
baseline_verdict,
destination_owners,
@@ -78,7 +78,7 @@ def _case_twin_pairs(
) -> list[tuple[str, str]]:
"""Each spelling left out, with the spelling the pack holds."""
held = {
_flat(dest, base_dest, flatten).lower(): _flat(dest, base_dest, flatten)
flat_arcname(dest, base_dest, flatten).lower(): flat_arcname(dest, base_dest, flatten)
for dest in seen_destinations
}
return sorted({(twin, held[twin.lower()]) for twin in twins if twin.lower() in held})
@@ -201,7 +201,7 @@ def _select_variants(
slot_undecidable: list[str] = []
if one_per_slot:
slot_drops, slot_undecidable = _slot_drops(
slot_drops, slot_undecidable = one_per_slot_drops(
config, emu_profiles, target_cores, region_groups, region_drops, held
)
region_drops = region_drops | slot_drops
@@ -214,7 +214,7 @@ def _select_variants(
return region_drops, region_fallbacks, slot_undecidable
def _slot_drops(
def one_per_slot_drops(
config: dict,
emu_profiles: dict | None,
target_cores: set[str] | None,
@@ -247,7 +247,7 @@ def _matches_an_alternative(fe: dict, local_path: str, profiles: dict) -> bool:
return False
# A sibling the code takes without a check (Raze's "BLOOD: Unknown
# Version") accepts whatever copy fills the slot.
if any(not _parse_validation(entry.get("validation")) for entry in siblings):
if any(not parse_validation(entry.get("validation")) for entry in siblings):
return True
actual = compute_hashes(local_path, frozenset({"sha1", "md5", "crc32"}))
for entry in siblings:
@@ -408,13 +408,13 @@ def _plan_platform_pack(
if cut is not None:
config, emu_profiles = cut.config, cut.profiles
narrowings = _narrowings(
narrowings = pack_narrowings(
opts.source, opts.regions, opts.target_name, opts.one_per_slot, opts.required_only,
no_game_data=opts.no_game_data,
)
zip_path = os.path.join(
output_dir,
_platform_pack_name(
platform_pack_name(
platform_name, platforms_dir, narrowings, opts.system_filter, opts.pack_name
),
)
@@ -432,7 +432,7 @@ def _plan_platform_pack(
name: emu_profiles[name]
for name in resolve_platform_cores(config, emu_profiles)
}
validation_index = _build_validation_index(platform_profiles)
validation_index = build_validation_index(platform_profiles)
validation_owners = destination_owners(platform_profiles)
slot_overrides = slots.pack_overrides(
config, emu_profiles or {}, db, zip_contents, opts.data_registry,
@@ -515,7 +515,7 @@ class _PlatformPackBuild:
verdict: Callable[[dict, str | None, str], tuple[str, str | None]]
judge: Callable[[dict, str | None, str], tuple[str | None, str | None]]
resolve_extra: Callable[[dict, str], tuple[str | None, str, str]]
placed: _Placed = field(init=False)
placed: Placed = field(init=False)
total_files: int = 0
core_count: int = 0
save_count: int = 0
@@ -532,10 +532,10 @@ class _PlatformPackBuild:
case_twins: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
self.placed = _Placed(self.plan.case_insensitive)
self.placed = Placed(self.plan.case_insensitive)
def _flat(self, path: str) -> str:
return _flat(path, self.plan.base_dest, self.plan.opts.flatten)
return flat_arcname(path, self.plan.base_dest, self.plan.opts.flatten)
def run(self) -> None:
if self.plan.opts.source != "truth":
@@ -642,7 +642,7 @@ class _PlatformPackBuild:
instr_path = (
f"{base_dest}/{instr_name}" if base_dest else instr_name
)
_write_generated_member(
write_generated_member(
self.zf,
self._flat(instr_path),
f"File needed: {file_entry['name']}\n\n{instructions}\n",
@@ -664,9 +664,9 @@ class _PlatformPackBuild:
if self.plan.opts.record is None and download_external(file_entry, tmp_path):
extract = file_entry.get("extract", False)
if extract and tmp_path.endswith(".zip"):
_extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf)
extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf)
else:
_add_pack_member(self.zf, tmp_path, self._flat(full_dest))
add_pack_member(self.zf, tmp_path, self._flat(full_dest))
self.file_status.setdefault(full_dest, "ok")
self.total_files += 1
else:
@@ -700,11 +700,11 @@ class _PlatformPackBuild:
if entry.get("path", "").startswith(agnostic_path)
and entry.get("name", "") and entry.get("name", "") != original_name
]
readme_text = _build_agnostic_rename_readme(dest_name, original_name, alt_names)
readme_text = build_agnostic_rename_readme(dest_name, original_name, alt_names)
readme_name = f"RENAMED_{dest_name}.txt"
readme_full = f"{plan.base_dest}/{readme_name}" if plan.base_dest else readme_name
if readme_full not in self.placed.destinations:
_write_generated_member(self.zf, self._flat(readme_full), readme_text)
write_generated_member(self.zf, self._flat(readme_full), readme_text)
self.placed.destinations.add(readme_full)
return local_path
@@ -766,7 +766,7 @@ class _PlatformPackBuild:
if full_dest not in self.placed.destinations:
self.case_twins.append(self._flat(full_dest))
return
if within is not None and not _same_bytes(local_path, within.get(self._flat(full_dest))):
if within is not None and not same_bytes(local_path, within.get(self._flat(full_dest))):
# The full pack holds another system's file here.
return
if self.file_status.get(full_dest) == "excluded":
@@ -777,11 +777,11 @@ class _PlatformPackBuild:
extract = file_entry.get("extract", False)
flat_dest = self._flat(full_dest)
if extract and local_path.endswith(".zip"):
_extract_zip_to_archive(local_path, flat_dest, self.zf)
extract_zip_to_archive(local_path, flat_dest, self.zf)
elif local_path.endswith(".zip"):
_add_zip_to_pack(local_path, flat_dest, self.zf, file_entry)
add_zip_to_pack(local_path, flat_dest, self.zf, file_entry)
else:
_add_pack_member(self.zf, local_path, flat_dest)
add_pack_member(self.zf, local_path, flat_dest)
self.total_files += 1
def _region_dropped(self, fe: dict) -> bool:
@@ -803,14 +803,14 @@ class _PlatformPackBuild:
# The systems asked for, with what their cores need: the split
# packs get exactly this, and a full pack of one system had none.
return _extras_for_systems(
_collect_emulator_extras(
collect_emulator_extras(
plan.config, opts.emulators_dir, plan.db, set(), plan.base_dest,
plan.emu_profiles, target_cores=opts.target_cores,
include_all=(opts.source == "truth"), undeclared=plan.undeclared,
),
opts.system_filter,
)
return _collect_emulator_extras(
return collect_emulator_extras(
plan.config,
opts.emulators_dir,
plan.db,
@@ -842,13 +842,13 @@ class _PlatformPackBuild:
# pack is extracted into the BIOS folder and cannot reach
# them, the installer places these files.
return
# Core extras: _collect_emulator_extras already adjusted
# Core extras: collect_emulator_extras already adjusted
# destinations for slug-based platforms. Apply the effective
# prefix (base_dest, or inferred from YAML when base_dest is
# empty, as RetroDECK infers "bios"). A file read below the save
# directory goes to the pack's save folder instead.
full_dest = extra_full_destination(
fe, _detect_extras_prefix(plan.config, plan.base_dest)
fe, detect_extras_prefix(plan.config, plan.base_dest)
)
if not full_dest:
return
@@ -872,12 +872,12 @@ class _PlatformPackBuild:
flat_dest = self._flat(full_dest)
within = plan.opts.within
if within is not None and not _same_bytes(local_path, within.get(flat_dest)):
if within is not None and not same_bytes(local_path, within.get(flat_dest)):
return
if local_path.endswith(".zip"):
_add_zip_to_pack(local_path, flat_dest, self.zf, fe)
add_zip_to_pack(local_path, flat_dest, self.zf, fe)
else:
_add_pack_member(self.zf, local_path, flat_dest)
add_pack_member(self.zf, local_path, flat_dest)
if self.file_status.get(full_dest) in ("missing", "excluded"):
self._core_fills_declaration(fe, full_dest)
self.placed.take(full_dest)
@@ -952,13 +952,13 @@ class _PlatformPackBuild:
required_only = plan.opts.required_only
seen_parents = self.placed.parents
added = 0
for src, full in _data_directory_members(
for src, full in data_directory_members(
pack_systems, plan.opts.data_registry, plan.platform_name, plan.base_dest,
self.placed.fold, self.placed.destinations, self.placed.lower,
seen_parents, required_only=required_only,
core_trees=core_trees,
):
_add_pack_member(self.zf, src, self._flat(full))
add_pack_member(self.zf, src, self._flat(full))
if isinstance(self.zf, PackRecord):
self.zf.trees.append(self._flat(full))
added += 1
@@ -970,14 +970,14 @@ class _PlatformPackBuild:
# them, as the manifest's case_variants are (Mesen-CE's bios.col
# beside the declared BIOS.col).
plan, opts = self.plan, self.plan.opts
unfolded = _collect_emulator_extras(
unfolded = collect_emulator_extras(
{**plan.config, "case_insensitive_fs": False}, opts.emulators_dir, plan.db, set(),
plan.base_dest, plan.emu_profiles, target_cores=opts.target_cores,
include_all=(opts.source == "truth"),
)
if opts.system_filter:
unfolded = _extras_for_systems(unfolded, opts.system_filter)
prefix = _detect_extras_prefix(plan.config, plan.base_dest)
prefix = detect_extras_prefix(plan.config, plan.base_dest)
unfolded_spares = self._spares(unfolded)
for fe in unfolded:
if opts.required_only and (fe.get("required") is False or id(fe) in unfolded_spares):
@@ -1004,7 +1004,7 @@ class _PlatformPackBuild:
if keeps_case and opts.source != "platform" and opts.precomputed_extras is None:
self._unfolded_twins()
save_count = self.save_count
readme_text = _build_readme(
readme_text = build_readme(
plan.platform_name, plan.platform_display, plan.base_dest, self.total_files,
len(plan.pack_systems),
source=opts.source,
@@ -1033,9 +1033,9 @@ class _PlatformPackBuild:
if keeps_case else []
),
)
_write_generated_member(self.zf, "README.txt", readme_text)
write_generated_member(self.zf, "README.txt", readme_text)
for marker in pack_markers(plan.platform_name, opts.target_name, plan.platforms_dir):
_write_generated_member(
write_generated_member(
self.zf,
self._flat(f"{plan.base_dest}/{marker}" if plan.base_dest else marker),
"",
@@ -1136,7 +1136,7 @@ def generate_pack(
with (
contextlib.nullcontext(opts.record) if opts.record is not None
else _writing_pack(plan.zip_path)
else writing_pack(plan.zip_path)
) as zf:
build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra)
build.run()
@@ -1181,7 +1181,7 @@ def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict
if source == "platform":
all_extras = []
elif emu_profiles:
all_extras = _collect_emulator_extras(
all_extras = collect_emulator_extras(
cut.config if cut else config, narrowing["emulators_dir"], db,
set(), base_dest, cut.profiles if cut else emu_profiles,
target_cores=target_cores, include_all=(source == "truth"),
@@ -1229,7 +1229,7 @@ def generate_split_packs(
# differently narrowed runs write into one another.
split_tags = "".join(
tag
for tag, _label in _narrowings(
for tag, _label in pack_narrowings(
narrowing["source"], narrowing["regions"], narrowing["target_name"],
narrowing["one_per_slot"], narrowing["required_only"],
no_game_data=narrowing["no_game_data"],
@@ -1244,7 +1244,7 @@ def generate_split_packs(
# Named by the stem the full pack reads: assembled here by hand, a '/' in
# a version nested the directory where the check never looked for it.
part_prefix = (
f"{_platform_pack_stem([platform_name], platform_name, platforms_dir)}{split_tags}"
f"{platform_pack_stem([platform_name], platform_name, platforms_dir)}{split_tags}"
)
split_dir = os.path.join(output_dir, f"{part_prefix}{group_tag}_Split")
if records is None:
@@ -1278,14 +1278,14 @@ def generate_split_packs(
if group_by == "manufacturer":
groups = _group_systems_by_manufacturer(systems, db, bios_dir)
else:
groups = {_system_display_name(sid): [sid] for sid in systems}
groups = {system_display_name(sid): [sid] for sid in systems}
all_extras = _split_extras(config, db, narrowing)
results = []
for group_name, group_system_ids in sorted(groups.items()):
group_extras = _extras_for_systems(all_extras, group_system_ids)
zip_path = part(
f"{part_prefix}_{_name_part(group_name, '_')}_BIOS_Pack.zip",
f"{part_prefix}_{file_name_part(group_name, '_')}_BIOS_Pack.zip",
{"system_filter": group_system_ids, "precomputed_extras": group_extras},
)
if zip_path:
+5 -5
View File
@@ -214,7 +214,7 @@ class ReadmeOptions(TypedDict, total=False):
case_twins: list[tuple[str, str]] | None
def _build_readme(
def build_readme(
platform_name: str,
platform_display: str,
base_dest: str,
@@ -235,7 +235,7 @@ def _build_readme(
where names keep their case (EmuDeck and RetroArch on Linux), where the
core asking for the other spelling finds nothing.
"""
reject_unknown("_build_readme", options, ReadmeOptions.__optional_keys__)
reject_unknown("build_readme", options, ReadmeOptions.__optional_keys__)
regions = options.get("regions")
launch_folders = options.get("launch_folders", 0)
sep = "=" * 50
@@ -366,7 +366,7 @@ def _region_info(regions: list[str] | None, fallback_systems: list[str] | None)
" Only the best-matching BIOS was kept for each system.\n"
)
if fallback_systems:
listed = "\n".join(f" {_group_label(s)}" for s in fallback_systems)
listed = "\n".join(f" {group_label(s)}" for s in fallback_systems)
region_info += (
"\n These systems have no BIOS in those regions, so every\n"
" BIOS file for them was kept:\n"
@@ -426,7 +426,7 @@ def _credits(contributors: list[dict] | None) -> str:
return credits + "\n"
def _build_agnostic_rename_readme(
def build_agnostic_rename_readme(
destination: str,
original: str,
alternatives: list[str],
@@ -445,7 +445,7 @@ def _build_agnostic_rename_readme(
return "\n".join(lines) + "\n"
def _group_label(group_id: str) -> str:
def group_label(group_id: str) -> str:
"""A region group as a reader names it: the system, or one core's slot."""
emulator, kind, rest = (group_id.split(":", 2) + ["", ""])[:3]
if kind == "variant" and rest:
+10 -10
View File
@@ -55,7 +55,7 @@ def _print_ground_truth(gt: list[dict], verbose: bool) -> None:
print(f" {_format_ground_truth_aggregate(gt)}")
def _discrepancy_keys(details: list[dict]) -> set[str]:
def discrepancy_keys(details: list[dict]) -> set[str]:
"""The DISCREPANCY lines _print_detail_entries prints for these details.
A file already reported MISSING or UNTESTED on its own ground is not
@@ -76,7 +76,7 @@ def _discrepancy_keys(details: list[dict]) -> set[str]:
# A platform entry that is not firmware, as the report names it.
_NOT_FIRMWARE = {
NOT_FIRMWARE = {
"game_data": "game data",
"unread": "no core the platform runs opens it",
}
@@ -149,7 +149,7 @@ def _print_missing_details(details: list[dict], seen: set[str], verbose: bool) -
key = f"{d['system']}/{d['name']}"
if key in seen:
continue
label = _NOT_FIRMWARE.get(d.get("category", BIOS))
label = NOT_FIRMWARE.get(d.get("category", BIOS))
if label:
# Counted on their own line, named on request.
if verbose:
@@ -228,7 +228,7 @@ def _print_undeclared_entry(
print(f" validates {'+'.join(checks)}")
def _split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], list[dict]]:
def split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], list[dict]]:
"""Game data, firmware the pack places, firmware it holds but cannot place.
Everything that is not game data is firmware the core loads, archives
@@ -242,7 +242,7 @@ def _split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], l
return game_data, placed, unplaced
def _core_required_missing(bios_files: list[dict]) -> list[dict]:
def core_required_missing(bios_files: list[dict]) -> list[dict]:
"""Core files a core cannot run without, absent from the collection.
A file bundled with the emulator (DaedalusX64's n64.psh, the shader
@@ -287,7 +287,7 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None:
if not undeclared and not (packed and any(packed.values())):
return
game_data, bios_files, unplaced = _split_undeclared(undeclared)
game_data, bios_files, unplaced = split_undeclared(undeclared)
# A file installed with its emulator is never collected, firmware or
# game data, required or not: cross_reference counts it apart. The
@@ -296,7 +296,7 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None:
bundled = [u for u in undeclared if not u["in_repo"] and u.get("bundled")]
game_data = [u for u in game_data if u["in_repo"] or not u.get("bundled")]
req_not_in_repo = _core_required_missing(bios_files)
req_not_in_repo = core_required_missing(bios_files)
req_hle_not_in_repo = [
u
for u in bios_files
@@ -460,15 +460,15 @@ def _print_platform_notices(result: dict, verbose: bool) -> None:
print(f" {line}")
fallbacks = result.get("region_fallbacks") or []
if fallbacks:
from packs.readme import _group_label
from packs.readme import group_label
print(f" No BIOS for the requested regions, all kept ({len(fallbacks)}): "
+ ", ".join(_group_label(g) for g in fallbacks))
+ ", ".join(group_label(g) for g in fallbacks))
not_firmware = result.get("missing_not_firmware") or {}
if not_firmware:
counts = ", ".join(
f"{len(dests)} {_NOT_FIRMWARE[category]}"
f"{len(dests)} {NOT_FIRMWARE[category]}"
for category, dests in not_firmware.items()
)
listed = "" if verbose else " (--verbose lists them)"
+10 -10
View File
@@ -10,7 +10,7 @@ from core.hashing import parse_md5_list
from model.profiles import entry_system_ids
from resolve import nativemode
from resolve.archives import archive_entry, holds_required_members
from resolve.collisions import _accepted_by_all, _content_sha1, _lists_hashes, _normalize
from resolve.collisions import accepted_by_all, content_sha1, lists_hashes, comparable_destination
from resolve.cores import resolve_platform_cores
from resolve.layout import system_dir_path
from resolve.localfile import resolution_is_hash_exact, resolve_local_file
@@ -374,7 +374,7 @@ def _slot_claims(
for claim in platform_claims(
config, db, base_dest, zip_contents, data_dir_registry
):
key = _normalize(claim.destination, fold)
key = comparable_destination(claim.destination, fold)
held = by_dest.get(key)
if held is not None and id(held.entry) in shipped:
continue
@@ -404,7 +404,7 @@ def _slot_claims(
profiles, db, base_dest, standalone_cores, zip_contents, data_dir_registry,
config=config,
):
key = _normalize(claim.destination, fold)
key = comparable_destination(claim.destination, fold)
platform = by_dest.get(key)
if platform is None or not claim.is_proven:
continue
@@ -619,25 +619,25 @@ def _satisfies(profile: Claim, platform: Claim, db: dict) -> bool:
# Two paths can hold one content: AmberELEC's bluemsx declarations
# resolve into the data/bluemsx cache, the profile's into bios/.
if profile.local_path and platform.local_path:
shipped = _content_sha1(platform.local_path, db)
if shipped is not None and shipped == _content_sha1(profile.local_path, db):
shipped = content_sha1(platform.local_path, db)
if shipped is not None and shipped == content_sha1(profile.local_path, db):
return True
members = profile.entry.get("members")
if members and platform.local_path:
return holds_required_members(platform.local_path, members)
if (
profile.local_path
and _lists_hashes(platform.entry)
and _accepted_by_all(profile.local_path, [platform.entry], db)
and lists_hashes(platform.entry)
and accepted_by_all(profile.local_path, [platform.entry], db)
):
return True
if platform.local_path and any(
_lists_hashes(label) and _accepted_by_all(platform.local_path, [label], db)
lists_hashes(label) and accepted_by_all(platform.local_path, [label], db)
for label in profile.accepts
):
return True
return bool(
platform.local_path
and _lists_hashes(profile.entry)
and _accepted_by_all(platform.local_path, [profile.entry], db)
and lists_hashes(profile.entry)
and accepted_by_all(platform.local_path, [profile.entry], db)
)
+4 -4
View File
@@ -10,7 +10,7 @@ from pathlib import PurePosixPath
from core.paths import REPO_ROOT
from packs.archive import PackRecord
from packs.emulatorpack import generate_emulator_pack
from packs.manifestentry import _manifest_entry
from packs.manifestentry import manifest_entry
def _placed_copies(copies: list[dict], dests: list[str]) -> list[dict]:
@@ -176,7 +176,7 @@ def _profile_copies(
return copies
def _standalone_copies(
def standalone_copies(
declared: list[dict], profiles: dict[str, dict], manifest_files: list[dict],
) -> list[dict]:
"""A manifest's standalone copies: the registry's, placed where this
@@ -193,7 +193,7 @@ def _standalone_copies(
STANDALONE_DIR = "standalone"
def _standalone_layouts(
def standalone_layouts(
profiles: dict[str, dict],
emulators_dir: str,
db: dict,
@@ -232,7 +232,7 @@ def _standalone_layouts(
)
items: list = []
for member in record.files:
entry, _size = _manifest_entry(
entry, _size = manifest_entry(
record.sources.get(member), member, [name], db, repo_root, {}
)
if entry is None:
+4 -4
View File
@@ -40,8 +40,8 @@ class Severity:
OK = "ok" # file verified
_STATUS_ORDER = {Status.OK: 0, Status.UNTESTED: 1, Status.MISSING: 2}
_SEVERITY_ORDER = {
STATUS_ORDER = {Status.OK: 0, Status.UNTESTED: 1, Status.MISSING: 2}
SEVERITY_ORDER = {
Severity.OK: 0,
Severity.INFO: 1,
Severity.WARNING: 2,
@@ -227,7 +227,7 @@ def verify_entry_sha1(
# Severity mapping per platform
def _emulator_severity(status: str, required: bool, hle_fallback: bool) -> str:
def emulator_severity(status: str, required: bool, hle_fallback: bool) -> str:
"""Severity when the emulator's own code is the check.
A file present but refused by the core's validation, or a different dump
@@ -274,7 +274,7 @@ def compute_severity(
return Severity.OK
def _storage_verdict(file_entry: dict, emulator_pack: bool) -> dict | None:
def storage_verdict(file_entry: dict, emulator_pack: bool) -> dict | None:
"""The result a storage tier fixes before any lookup, as the builder sees it.
A user_provided entry is never taken from the collection: a platform pack
+10 -10
View File
@@ -458,7 +458,7 @@ def _tree_members(
from packs import datatrees
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packs.paths import _flat
from packs.paths import flat_arcname
config = load_platform_config(platform, platforms_dir)
base_dest = config.get("base_destination", "")
@@ -468,12 +468,12 @@ def _tree_members(
)
members: dict[str, int] = {}
with contextlib.redirect_stdout(io.StringIO()):
for src, full in datatrees._data_directory_members(
for src, full in datatrees.data_directory_members(
config.get("systems", {}), registry,
platform, base_dest, False, set(), set(), set(),
core_trees=core_trees,
):
members[_flat(full, base_dest, True)] = os.path.getsize(src)
members[flat_arcname(full, base_dest, True)] = os.path.getsize(src)
return members
@@ -588,7 +588,7 @@ def check_emulator_packs(
profiles_for_systems,
select_emulator_profiles,
)
from model.systems import _norm_system_id
from model.systems import norm_system_id
from core.ziptools import build_zip_contents_index
from model.database import load_database
@@ -599,7 +599,7 @@ def check_emulator_packs(
def compare(names: list[str], standalone: bool, label: str, **narrowing: object) -> bool:
record = archive.PackRecord()
was_offline = packresolve._OFFLINE
was_offline = packresolve.OFFLINE
# The pack is built offline: verify counts a release asset the cache
# lacks the same way, missing, as the narrowed-pack step does.
packresolve.set_offline(True)
@@ -643,7 +643,7 @@ def check_emulator_packs(
# rule that only goes wrong when two profiles share a path (the bluemsx
# tree beside msx-emu's files) never meets in a one-profile pack.
systems = sorted({
_norm_system_id(str(sid))
norm_system_id(str(sid))
for profile in profiles.values()
if profile.get("type") not in ("launcher", "alias") and profile.get("role") != "test"
for sid in profile.get("systems") or []
@@ -668,7 +668,7 @@ def check_emulator_packs(
return all_ok and systems_ok
# How each _narrowings() dimension of a platform pack is compared by
# How each pack_narrowings() dimension of a platform pack is compared by
# check_narrowed_packs, or why it is not. A test reads the builder's
# signature against these two tables, so a new narrowing fails it until it
# is compared or a reason is written here. Emulator packs have their own
@@ -772,7 +772,7 @@ def check_narrowed_packs(
list_registered_platforms(platforms_dir),
platforms_dir,
)
was_offline = packresolve._OFFLINE
was_offline = packresolve.OFFLINE
packresolve.set_offline(True)
all_ok = True
compared = 0
@@ -881,7 +881,7 @@ def check_split_packs(
list_registered_platforms(platforms_dir),
platforms_dir,
)
was_offline = packresolve._OFFLINE
was_offline = packresolve.OFFLINE
packresolve.set_offline(True)
all_ok = True
try:
@@ -900,7 +900,7 @@ def check_split_packs(
packs_platformpack.generate_split_packs(
platform, platforms_dir, db, "bios", "", records=parts, **args,
)
lines = split_differences(full, parts, archive._same_bytes)
lines = split_differences(full, parts, archive.same_bytes)
if lines:
all_ok = False
print(f" {platform} --split: {len(lines)} differences")
+5 -5
View File
@@ -25,7 +25,7 @@ from core.statefile import now_iso
from model import measurements as mr
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from model.systems import _norm_system_id
from model.systems import norm_system_id
from model.targets import load_target_config
from probes.content import Content, load_content, load_file, verify_identity
from probes.cores import BUILDBOT, safe_extract_so
@@ -72,8 +72,8 @@ class CoreChoice:
def platform_system(config: dict, system: str) -> str | None:
"""The platform's own id of a system, compared on the normalised id."""
wanted = _norm_system_id(system)
matches = sorted(s for s in config.get("systems") or {} if _norm_system_id(s) == wanted)
wanted = norm_system_id(system)
matches = sorted(s for s in config.get("systems") or {} if norm_system_id(s) == wanted)
return matches[0] if matches else None
@@ -105,11 +105,11 @@ def so_names(name: str, profile: dict, buildbot: set[str], target: set[str] | No
def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot: set[str],
target: set[str] | None) -> list[CoreChoice]:
wanted = _norm_system_id(system)
wanted = norm_system_id(system)
out: list[CoreChoice] = []
for name in sorted(resolve_platform_cores(config, profiles, target)):
profile = profiles[name]
if wanted not in {_norm_system_id(s) for s in profile.get("systems") or ()}:
if wanted not in {norm_system_id(s) for s in profile.get("systems") or ()}:
continue
if not libretro_build_runs(name, profile, config):
continue
+15 -15
View File
@@ -22,15 +22,15 @@ sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from profiling import version_basis
from model.systems import _norm_system_id, system_index
from model.systems import norm_system_id, system_index
from core.github import github_token
from model.profiles import load_emulator_profiles
from core.cli import suggest_names
from profiling.bump import DEFAULT_CACHE, write_version
from profiling.realign import realign_prose
from profiling.reports import ProfileReport
from profiling.run import _WRITTEN, _emit, _read_one
from profiling.triage import PROGRESS_SECONDS, _Progress, _interrupted
from profiling.run import WRITTEN_PROFILES, emit_reports, read_one_profile
from profiling.triage import PROGRESS_SECONDS, Progress, print_interrupted
from profiling.yamledit import YamlWriteError
ANON_QUOTA = 60
@@ -289,9 +289,9 @@ def project_base() -> str:
is HEAD, and --changed --strict found nothing and passed while the PR's
CI then failed. validate_pr.py resolves the same line the same way.
"""
from core.gitclone import _git_lines as git_lines, _project_main_line
from core.gitclone import git_lines as git_lines, project_main_line
line = _project_main_line()
line = project_main_line()
if line:
return line
for remote in ("upstream", "origin"):
@@ -328,13 +328,13 @@ def select_profiles(profiles: dict, args: argparse.Namespace) -> dict:
# --system matches as verify.py --list-systems lists and --system selects:
# by normalized id, so `saturn` reaches the profiles declaring sega-saturn.
wanted_system = _norm_system_id(args.system) if args.system else None
wanted_system = norm_system_id(args.system) if args.system else None
selected = {}
for name, profile in sorted(profiles.items()):
if profile.get("type") == "alias" or profile.get("role") == "test":
continue
if wanted_system and wanted_system not in {
_norm_system_id(str(s)) for s in profile.get("systems") or []
norm_system_id(str(s)) for s in profile.get("systems") or []
}:
continue
if args.type_ and profile.get("type") != args.type_:
@@ -589,16 +589,16 @@ def main() -> None:
f"{PROGRESS_SECONDS} s. --offline answers from the cache alone.",
file=sys.stderr, flush=True,
)
progress = _Progress(len(selected), "read", quiet)
progress = Progress(len(selected), "read", quiet)
complete = True
try:
for name, profile in selected.items():
progress.step(len(reports), name)
_read_one(args, name, profile, reports, failed, writes)
read_one_profile(args, name, profile, reports, failed, writes)
except KeyboardInterrupt:
# What was read is still worth printing: a ranking of 200 profiles
# beats none after 15 minutes.
_interrupted(len(reports), len(selected), "the output covers those read")
print_interrupted(len(reports), len(selected), "the output covers those read")
complete = False
# --changed-only narrows every output, not the text report alone: the
@@ -607,7 +607,7 @@ def main() -> None:
report for report in reports
if not args.changed_only or report.needs_review() or report.name in failed
]
complete = _emit(args, selected, reports, shown) is not False and complete
complete = emit_reports(args, selected, reports, shown) is not False and complete
_refresh_source_paths(args)
if not complete:
raise SystemExit(130)
@@ -631,7 +631,7 @@ def _run_realign(args: argparse.Namespace, selected: dict) -> None:
):
print(f"{name}: {line}")
if profile_path.read_bytes() != before:
_WRITTEN.add(name)
WRITTEN_PROFILES.add(name)
except upstream.UpstreamError as exc:
print(f"{name}: {exc}", file=sys.stderr)
failed.add(name)
@@ -651,16 +651,16 @@ def _refresh_source_paths(args: argparse.Namespace) -> None:
--fetch by hand. A run that writes nothing, or makes no request, leaves
it alone.
"""
if not _WRITTEN or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"):
if not WRITTEN_PROFILES or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"):
return
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from sitegen import sources
from core.artifacts import write_if_changed
# The run loaded the profiles before writing them, and the loader caches
# by directory: read again, the record described the pins just replaced
# (linapple, then ten profiles in one advance).
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
held, unread = sources.build_source_paths(
profiles, [sources.TREE_CACHE], fetch=True
+6 -6
View File
@@ -15,7 +15,7 @@ import yaml
from core import upstream
from core.hashing import parse_hash_list
from model.sourceref import RefPart, _prose_runs, ref_prose_text, ref_role, source_ref_values
from model.sourceref import RefPart, prose_runs, ref_prose_text, ref_role, source_ref_values
from profiling.repos import declared_repositories
@@ -155,7 +155,7 @@ def symlink_target(path: str, lines: list[str] | None) -> str | None:
return None if resolved.startswith("..") or resolved == path else resolved
def _anchor_tokens(entry: dict) -> list[str]:
def anchor_tokens(entry: dict) -> list[str]:
"""Values worth searching for when a cited line misses its subject.
Both the content values and the set name are searched, because profiles
@@ -309,7 +309,7 @@ def comment_citations(
continue
comment = line[column + 1:].rstrip("\r\n")
shift = column + 1
for _, path_span, run_spans, parts, run, _ in _prose_runs(comment, known):
for _, path_span, run_spans, parts, run, _ in prose_runs(comment, known):
citations.append(Citation(
field=f"comment line {number + 1}", kind="prose", ref=run,
line=number,
@@ -346,7 +346,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation]
holder=holder, key=key, label=label,
))
if isinstance(value, str):
for line, path_span, spans, parts, run, joined_at in _prose_runs(
for line, path_span, spans, parts, run, joined_at in prose_runs(
ref_prose_text(value), known
):
citations.append(Citation(
@@ -355,7 +355,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation]
parts=parts, wrapped=bool(joined_at), joined_at=joined_at,
))
continue
for line, path_span, spans, parts, run, joined_at in _prose_runs(
for line, path_span, spans, parts, run, joined_at in prose_runs(
value, known
):
citations.append(Citation(
@@ -368,7 +368,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation]
return citations
def _citation_key(ref: str) -> str:
def citation_key(ref: str) -> str:
"""A citation compared without the spacing the author chose.
A recale rewrites the located tokens and leaves the sentence alone, so
+6 -6
View File
@@ -194,20 +194,20 @@ def tree_diff(result: CompareResult, ref_dirs: set[str]) -> list[str]:
return lines
def _cited_paths(report: ProfileReport) -> list[str]:
def cited_paths(report: ProfileReport) -> list[str]:
return sorted(
{part.new_path or part.part.path for e in report.entries for part in e.parts}
)
def _detect(
def detect_upstream_changes(
args: argparse.Namespace, profile: dict, report: ProfileReport,
repo: upstream.Repo,
) -> None:
names, hashes = declared_names(profile), declared_hashes(profile)
new_files: list[dict] = []
new_hashes: list[dict] = []
for path in _cited_paths(report):
for path in cited_paths(report):
head_lines = upstream.fetch_file(
repo, report.head, path, args.cache_dir, args.offline
)
@@ -259,7 +259,7 @@ def _print_detection(report: ProfileReport) -> None:
print(f" new {item['kind']}: {item['path']} {item['value']}")
def _print_extras(
def print_extras(
args: argparse.Namespace, profile: dict, report: ProfileReport
) -> None:
"""Optional per-profile sections beyond the ref report.
@@ -288,7 +288,7 @@ def _print_extras_from(
repo: upstream.Repo,
) -> None:
if args.full_diff:
for path in _cited_paths(report):
for path in cited_paths(report):
if args.ref and args.ref not in path:
continue
pin_lines = (
@@ -312,6 +312,6 @@ def _print_extras_from(
)
# The repository root is a directory like any other: dropping the
# empty dirname would turn the filter off and list the whole tree.
ref_dirs = {posixpath.dirname(p) for p in _cited_paths(report)}
ref_dirs = {posixpath.dirname(p) for p in cited_paths(report)}
for line in tree_diff(comparison, ref_dirs):
print(f" {line}")
+5 -5
View File
@@ -15,7 +15,7 @@ from profiling.citations import Citation
_RANGE_TOKEN_RE = re.compile(r"\d+(?:-\d+)?")
def _run_after_moves(
def run_after_moves(
parts: Sequence[RefPart],
moves: dict[int, tuple[int, int, str | None]],
run: str = "",
@@ -108,7 +108,7 @@ def _scalar(holder: object, key: object) -> object:
raise TypeError(f"no scalar under {key!r} in a {type(holder).__name__}")
def _set_scalar(holder: object, key: object, value: str) -> None:
def set_scalar(holder: object, key: object, value: str) -> None:
"""Replace the value a citation's holder keeps under its key."""
if isinstance(holder, dict):
holder[key] = value
@@ -275,7 +275,7 @@ def _edit_scalar_run(
edits.applied.append(f"{citation.field}: {citation.ref} -> {recaled}")
def _apply_prose_edits(
def apply_prose_edits(
text: str, jobs: list[tuple[Citation, dict]], document: object = None
) -> tuple[str, list[str], list[str]]:
"""Rewrite prose citation tokens in place, nothing else.
@@ -297,7 +297,7 @@ def _apply_prose_edits(
for citation, moves in jobs:
replacements = _prose_replacements(citation, moves)
recaled = _run_after_moves(citation.parts, moves, citation.ref)
recaled = run_after_moves(citation.parts, moves, citation.ref)
if citation.in_comment:
_edit_comment_run(edits, citation, replacements, recaled)
else:
@@ -311,7 +311,7 @@ def _apply_prose_edits(
value_lines = value.splitlines()
for line_number, spans in by_line.items():
value_lines[line_number] = _replace_spans(value_lines[line_number], spans)
_set_scalar(holder, key, "\n".join(value_lines) + (
set_scalar(holder, key, "\n".join(value_lines) + (
"\n" if value.endswith("\n") else ""
))
return "\n".join(lines) + trailing, edits.applied, edits.left
+6 -6
View File
@@ -14,8 +14,8 @@ import yaml
from core import upstream
from model.sourceref import RefPart
from profiling.anchoring import anchor_block
from profiling.citations import Citation, _citation_key, collect_citations, is_external_citation
from profiling.proseedit import _apply_prose_edits, _run_after_moves
from profiling.citations import Citation, citation_key, collect_citations, is_external_citation
from profiling.proseedit import apply_prose_edits, run_after_moves
from profiling.repos import declared_repositories
from profiling.yamledit import apply_edit
@@ -383,7 +383,7 @@ class _ProseHistory:
def _carried_by(past: dict) -> set[tuple[str, str]]:
return {
(c.field, _citation_key(c.ref))
(c.field, citation_key(c.ref))
for c in collect_citations(past) if c.kind == "prose"
}
@@ -510,18 +510,18 @@ def realign_prose(
# one of its citations is corrected by hand, and dating the whole field
# from that commit put idtech4a++'s untouched Game.java:69-72 under the
# current pin, so the stale range was never offered again.
keys = [(c.field, _citation_key(c.ref)) for c in citations]
keys = [(c.field, citation_key(c.ref)) for c in citations]
dated = _date_prose(path, document, keys, history)
messages, jobs = _prose_jobs(document, citations, dated, declared, cache_dir, offline)
if dry_run:
messages.extend(
f"would recale {citation.field}: {citation.ref} -> "
f"{_run_after_moves(citation.parts, moves, citation.ref)}"
f"{run_after_moves(citation.parts, moves, citation.ref)}"
for citation, moves in jobs
)
return messages
new_text, applied, left = _apply_prose_edits(text, jobs, document)
new_text, applied, left = apply_prose_edits(text, jobs, document)
messages.extend(applied)
messages.extend(f"left in place: {item}" for item in left)
if applied:
+16 -16
View File
@@ -10,9 +10,9 @@ import yaml
from core import upstream
from model.sourceref import ref_role, split_outside_parentheses, split_source_ref
from profiling.anchoring import PartResult, REBASE_STATUSES, REVIEW_STATUSES
from profiling.citations import Citation, _citation_key, collect_citations
from profiling.proseedit import _apply_prose_edits, _run_after_moves, _set_scalar
from profiling.reports import EntryReport, ProfileReport, _original_part, _rendered_part
from profiling.citations import Citation, citation_key, collect_citations
from profiling.proseedit import apply_prose_edits, run_after_moves, set_scalar
from profiling.reports import EntryReport, ProfileReport, original_part, rendered_part
from profiling.repos import declared_repositories
from profiling.yamledit import YamlWriteError, apply_edit, find_field_line, replace_field_line
@@ -107,7 +107,7 @@ def pin_blockers(report: ProfileReport, accept_changed: bool = False) -> list[st
if not any(
part.status in movable
and part.start is not None
and _rendered_part(part) != _original_part(part)
and rendered_part(part) != original_part(part)
for part in entry.parts
):
continue
@@ -156,7 +156,7 @@ def attribute_refs(path: Path, report: ProfileReport, profile: dict) -> list[str
continue
rendered = []
for part in entry.parts:
raw = part.part.raw or _original_part(part)
raw = part.part.raw or original_part(part)
role, bare = ref_role(raw)
written_path = bare.startswith(part.part.path)
owner = role_of.get(part.repo or "", primary) if part.repo else primary
@@ -185,7 +185,7 @@ def _moved_by_hand(entry: EntryReport, statuses: tuple[str, ...]) -> bool:
return any(
part.status in statuses
and part.start is not None
and _rendered_part(part) != _original_part(part)
and rendered_part(part) != original_part(part)
for part in entry.parts
)
@@ -196,12 +196,12 @@ def _recaled_ref(entry: EntryReport, statuses: tuple[str, ...]) -> str | None:
touched = False
for part in entry.parts:
if part.status in statuses and part.start is not None:
recaled = _rendered_part(part)
if recaled != _original_part(part):
recaled = rendered_part(part)
if recaled != original_part(part):
touched = True
rendered.append(recaled)
else:
rendered.append(_original_part(part))
rendered.append(original_part(part))
return ", ".join(rendered) if touched else None
@@ -285,10 +285,10 @@ def rebase_refs(
text, "source_ref", entry.source_ref, new_ref, cursor
)
cursor = index + 1
_set_scalar(citation.holder, citation.key, new_ref)
set_scalar(citation.holder, citation.key, new_ref)
applied.append(f"{entry.source_ref} -> {new_ref}")
text, prose_applied, left = _apply_prose_edits(text, prose_jobs, document)
text, prose_applied, left = apply_prose_edits(text, prose_jobs, document)
refused.extend(left)
if refused:
# A citation left on the pinned lines holds the pin, so writing the
@@ -336,7 +336,7 @@ def _pending_refs(
for part in entry.parts
if part.status in movable
and part.start is not None
and _rendered_part(part) != _original_part(part)
and rendered_part(part) != original_part(part)
)
return pending
@@ -348,7 +348,7 @@ def _pending_prose(
pool: dict[tuple[str, str], int] = {}
for citation in collect_citations(document, text):
if citation.kind == "prose":
slot = (citation.field, _citation_key(citation.ref))
slot = (citation.field, citation_key(citation.ref))
pool[slot] = pool.get(slot, 0) + 1
pending = 0
for entry in report.entries or []:
@@ -361,12 +361,12 @@ def _pending_prose(
if any(_part_moves(part, movable) for part in entry.parts):
pending += 1
continue
rendered = _run_after_moves(
rendered = run_after_moves(
[p.part for p in entry.parts], moves, entry.source_ref
)
if _citation_key(rendered) == _citation_key(entry.source_ref):
if citation_key(rendered) == citation_key(entry.source_ref):
continue
slot = (entry.field, _citation_key(rendered))
slot = (entry.field, citation_key(rendered))
if pool.get(slot, 0) > 0:
pool[slot] -= 1
continue
+5 -5
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
from dataclasses import asdict, dataclass, field
from core import upstream
from model.sourceref import _ANNOTATION_RE, _trim_prose
from model.sourceref import ANNOTATION_RE, trim_prose
from profiling.anchoring import PartResult, REVIEW_STATUSES
from profiling.versions import VersionReport
@@ -142,20 +142,20 @@ def _render_span(path: str, start: int | None, end: int | None) -> str:
return f"{path}:{start}"
def _original_part(part: PartResult) -> str:
def original_part(part: PartResult) -> str:
"""The part exactly as the profile writes it today."""
return part.part.raw or _render_span(
part.part.path, part.part.start, part.part.end
)
def _rendered_part(part: PartResult) -> str:
def rendered_part(part: PartResult) -> str:
"""The part rewritten onto its new location, annotation preserved."""
span = _render_span(part.new_path or part.part.path, part.start, part.end)
raw = part.part.raw
if not raw:
return span
located = _trim_prose(_ANNOTATION_RE.sub("", raw).strip())
located = trim_prose(ANNOTATION_RE.sub("", raw).strip())
# `stella src/emucore/Cart.cxx:120` names the repository the lines are
# in. The path was read without that word, and a recale wrote it back
# without it: the attribution went with the old line numbers.
@@ -182,7 +182,7 @@ def _part_line(part: PartResult) -> str:
detail += f" ({part.reason})"
if part.repo:
detail += f" [{part.repo}]"
return f" {_original_part(part)} {detail}"
return f" {original_part(part)} {detail}"
def _report_header(report: ProfileReport) -> list[str]:
+1 -1
View File
@@ -407,6 +407,6 @@ def build_revision(profile: dict, platform: str) -> str | None:
return None
def _on_own_revision(view: RepoView, tagged: dict[tuple[str, str], str]) -> bool:
def reads_own_revision(view: RepoView, tagged: dict[tuple[str, str], str]) -> bool:
"""Whether a view is read at its own revision: on HEAD, or on its tag."""
return view.pin == view.head or (view.repo.host, view.repo.slug) in tagged
+5 -5
View File
@@ -29,7 +29,7 @@ from profiling.anchoring import (
)
from profiling.citations import (
Citation,
_anchor_tokens,
anchor_tokens,
cites_another_version,
collect_citations,
entry_hashes,
@@ -42,7 +42,7 @@ from profiling.reports import EntryReport, ProfileReport
from profiling.repos import (
PIN,
RepoView,
_on_own_revision,
reads_own_revision,
build_revision,
declared_repositories,
detect_pinned_tag,
@@ -187,7 +187,7 @@ def _gather_refs(
for p in split_source_ref(citation.ref)
]
refs.append((
display, citation.ref, _anchor_tokens(entry),
display, citation.ref, anchor_tokens(entry),
entry_hashes(entry), parts, citation,
))
else:
@@ -314,7 +314,7 @@ def _record_revisions(
report.orphaned = [
f"{view.repo.slug}: pin {view.pin[:8]} is no ancestor of {view.head[:8]}"
for view in views
if not _on_own_revision(view, tagged)
if not reads_own_revision(view, tagged)
and upstream.compare(
view.repo, view.pin, view.head, cache_dir, offline
).diverged
@@ -397,7 +397,7 @@ class _Resolver:
return next(iter(lent)) if len(lent) == 1 else ""
def on_own_revision(self, view: RepoView) -> bool:
return _on_own_revision(view, self.tagged)
return reads_own_revision(view, self.tagged)
def trees_in_order(self) -> Iterable[list[str] | None]:
"""Pin trees before HEAD trees, each read only when reached."""
+13 -13
View File
@@ -13,7 +13,7 @@ import yaml
from core import upstream
from profiling.bump import bump_commit, pins_changed
from profiling.detection import _detect, _print_extras
from profiling.detection import detect_upstream_changes, print_extras
from profiling.realign import realign_prose
from profiling.rebase import attribute_refs, rebase_refs
from profiling.reports import (
@@ -25,10 +25,10 @@ from profiling.reports import (
)
from profiling.repos import select_repo
from profiling.resolver import build_report
from profiling.triage import _print_triage
from profiling.triage import print_triage
from profiling.versions import (
_newer_release,
_passed_release,
newer_release,
latest_passed_release,
check_version,
page_version,
version_warning,
@@ -135,7 +135,7 @@ def _promote(
file=sys.stderr,
)
return False
_WRITTEN.add(name)
WRITTEN_PROFILES.add(name)
return True
@@ -254,7 +254,7 @@ def _attach_detection(
if repo is None:
return
try:
_detect(args, profile, report, repo)
detect_upstream_changes(args, profile, report, repo)
except upstream.RateLimitError:
raise
except upstream.UpstreamError as exc:
@@ -287,8 +287,8 @@ def _attach_version(
relation = upstream.ancestry(
repo, version.tag_commit, report.pin, args.cache_dir, args.offline
)
passed = _passed_release(args, repo, version, report.pin)
newer = None if passed or profile.get("pin_frozen") else _newer_release(
passed = latest_passed_release(args, repo, version, report.pin)
newer = None if passed or profile.get("pin_frozen") else newer_release(
args, repo, version, report.pin
)
except upstream.RateLimitError:
@@ -303,7 +303,7 @@ def _attach_version(
)
def _read_one(
def read_one_profile(
args: argparse.Namespace,
name: str,
profile: dict,
@@ -344,7 +344,7 @@ def _read_one(
# Profiles this run wrote. Their new pins name trees the site's record of
# cited source paths does not hold yet.
_WRITTEN: set[str] = set()
WRITTEN_PROFILES: set[str] = set()
def _build_full_report(
@@ -402,7 +402,7 @@ def _build_full_report(
return report
def _emit(
def emit_reports(
args: argparse.Namespace,
selected: dict,
reports: list[ProfileReport],
@@ -425,10 +425,10 @@ def _emit(
print(url)
return None
if args.triage:
return _print_triage(args, selected, shown)
return print_triage(args, selected, shown)
for report in shown:
print(format_report(report, args.changed_only))
_print_extras(args, selected[report.name], report)
print_extras(args, selected[report.name], report)
print()
if args.changed_only:
_print_elided(reports, len(shown), frozenset(report.name for report in shown))
+7 -7
View File
@@ -7,7 +7,7 @@ import sys
import time
from core import upstream
from profiling.detection import _cited_paths
from profiling.detection import cited_paths
from profiling.reports import ProfileReport, triage_state
from profiling.repos import select_repo
from profiling.versions import VersionReport, check_version
@@ -51,7 +51,7 @@ def drift_score(
return score
class _Progress:
class Progress:
"""A stderr line every PROGRESS_SECONDS while a pass asks the forges."""
def __init__(self, total: int, doing: str, quiet: bool) -> None:
@@ -65,25 +65,25 @@ class _Progress:
self.last = now
def _interrupted(done: int, total: int, what: str) -> None:
def print_interrupted(done: int, total: int, what: str) -> None:
print(f"interrupted after {done} of {total} profiles: {what}", file=sys.stderr, flush=True)
def _print_triage(
def print_triage(
args: argparse.Namespace, selected: dict, reports: list[ProfileReport]
) -> bool:
"""Profiles ranked by drift, worst first. False when Ctrl-C cut the
scoring short: the ranking then covers the profiles scored."""
ranked: list[tuple[int, ProfileReport, str]] = []
sampled = 0
progress = _Progress(len(reports), "scored", args.offline or len(reports) < 2)
progress = Progress(len(reports), "scored", args.offline or len(reports) < 2)
complete = True
try:
for done, report in enumerate(reports):
progress.step(done, report.name)
sampled += _score(args, selected, report, ranked)
except KeyboardInterrupt:
_interrupted(len(ranked), len(reports), "the ranking covers those scored")
print_interrupted(len(ranked), len(reports), "the ranking covers those scored")
complete = False
if sampled:
# One line for the run: a notice per profile buried the ranking
@@ -117,7 +117,7 @@ def _score(
sampled = False
repo = select_repo(profile)
if report.head and repo is not None:
paths = _cited_paths(report)
paths = cited_paths(report)
try:
version = check_version(profile, repo, args.cache_dir, args.offline)
for path in paths[:TRIAGE_PATH_SAMPLE]:
+2 -2
View File
@@ -149,7 +149,7 @@ def _later_number(candidate: str, declared: str) -> bool:
return high[0] == low[0] and high > low
def _newer_release(
def newer_release(
args: argparse.Namespace,
repo: upstream.Repo,
version: VersionReport | None,
@@ -178,7 +178,7 @@ def _newer_release(
return published
def _passed_release(
def latest_passed_release(
args: argparse.Namespace,
repo: upstream.Repo,
version: VersionReport | None,
+1 -1
View File
@@ -32,7 +32,7 @@ def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]:
platforms = list_release_pack_platforms(platforms_dir)
owners: dict[str, list[str]] = {}
for platform, names in naming._expected_pack_names(
for platform, names in naming.expected_pack_names(
platforms, platforms_dir, None, None
).items():
for name in names:
+3 -3
View File
@@ -136,7 +136,7 @@ def _member_held(member: dict, crcs: frozenset[str], names: frozenset[str]) -> b
return named
def _holding_members(paths: list[str], members: list[dict]) -> list[str]:
def holding_members(paths: list[str], members: list[dict]) -> list[str]:
"""The same-named archives holding the most required members, then the most members.
FBNeo reads neocd.bin and 000-lo.lo inside neocdz.zip. The primary copy,
@@ -157,7 +157,7 @@ def _holding_members(paths: list[str], members: list[dict]) -> list[str]:
return [path for path in paths if scores[path] == best]
def _covering_archives(paths: list[str]) -> list[str]:
def covering_archives(paths: list[str]) -> list[str]:
"""Same-named archives, those holding every ROM each other copy holds.
Without a declared layout, a primary that is a superset of the other
@@ -185,7 +185,7 @@ def _covering_archives(paths: list[str]) -> list[str]:
_unreadable_archives: set[str] = set()
def _warn_unreadable_archive(path: str, exc: Exception) -> None:
def warn_unreadable_archive(path: str, exc: Exception) -> None:
"""Say once that an archive on disk cannot be read.
Skipped in silence, a truncated ZIP came out as not_found or
+14 -14
View File
@@ -16,10 +16,10 @@ from dataclasses import dataclass, field
from pathlib import Path
from model.systems import _norm_system_id
from model.systems import norm_system_id
from resolve.cores import resolve_platform_cores, unresolved_platform_cores
from resolve.reconcile import HASH_FIELDS, NativeSystem, _hash_values
from resolve.launchers import _names as launcher_names
from resolve.reconcile import HASH_FIELDS, NativeSystem, hash_values
from resolve.launchers import record_names as launcher_names
def _tails(path: str) -> list[str]:
@@ -29,17 +29,17 @@ def _tails(path: str) -> list[str]:
def _entry_hashes(entry: dict) -> set[str]:
values = {v for f in HASH_FIELDS for v in _hash_values(entry, f)}
values = {v for f in HASH_FIELDS for v in hash_values(entry, f)}
for member in entry.get("contents") or []:
if isinstance(member, dict):
values |= {v for f in HASH_FIELDS for v in _hash_values(member, f)}
values |= {v for f in HASH_FIELDS for v in hash_values(member, f)}
return values
def _declared_hashes(entry: dict) -> dict[str, set[str]]:
"""Hash field -> the values a platform entry declares, alt_md5 as md5."""
found = {f: set(_hash_values(entry, f)) for f in HASH_FIELDS}
found["md5"] |= set(_hash_values(entry, "alt_md5"))
found = {f: set(hash_values(entry, f)) for f in HASH_FIELDS}
found["md5"] |= set(hash_values(entry, "alt_md5"))
return {f: values for f, values in found.items() if values}
@@ -53,7 +53,7 @@ def _contradicts(profile_entry: dict, declared: dict[str, set[str]]) -> bool:
"""True when both sides state the same kind of hash and no value agrees:
the profile entry describes another dump under the same name."""
for field_name, values in declared.items():
own = set(_hash_values(profile_entry, field_name))
own = set(hash_values(profile_entry, field_name))
if own and not set(values) & set(own):
return True
return False
@@ -138,7 +138,7 @@ class ReadEvidence:
if names & self.names or (tails and tails[-1] in self.names):
return "name"
hashes = {
v for f in (*HASH_FIELDS, "alt_md5") for v in _hash_values(entry, f)
v for f in (*HASH_FIELDS, "alt_md5") for v in hash_values(entry, f)
}
if hashes & self.hashes:
return "hash"
@@ -196,7 +196,7 @@ class ProofIndex:
tails = _tails(destination)
last = {tails[-1]} if tails else set()
hashes = {
v for f in (*HASH_FIELDS, "alt_md5") for v in _hash_values(entry, f)
v for f in (*HASH_FIELDS, "alt_md5") for v in hash_values(entry, f)
}
# "/" + d in "/" + path: d is a run of whole segments ending in "/",
# so it is a run of the path's segments before the last one.
@@ -275,7 +275,7 @@ def removal_candidates(
by_system: dict[str, list[str]] = {}
for key in sorted(examined):
for sid in profiles[key].get("systems") or []:
by_system.setdefault(_norm_system_id(str(sid)), []).append(key)
by_system.setdefault(norm_system_id(str(sid)), []).append(key)
romset_cores = {key for key in examined if _loads_romsets(profiles[key])}
@@ -287,7 +287,7 @@ def removal_candidates(
if evidence.proof(entry.platform, entry.destination) is not None:
continue
slug = system_of.get(id(entry.platform), entry.native_system)
cores = by_system.get(_norm_system_id(slug), [])
cores = by_system.get(norm_system_id(slug), [])
readers = (
[c for c in cores if c in romset_cores]
if entry.name.casefold().endswith(_ARCHIVES) else []
@@ -370,7 +370,7 @@ class EntryCategories:
self._by_system: dict[str, list[str]] = {}
for key in sorted(examined):
for sid in profiles[key].get("systems") or []:
self._by_system.setdefault(_norm_system_id(str(sid)), []).append(key)
self._by_system.setdefault(norm_system_id(str(sid)), []).append(key)
# Where the platform says which cores run a system, those settle its
# entries: an unprofiled core of another system has no say.
self._system_runs: dict[str, tuple[list[str], list[str]]] = {}
@@ -461,7 +461,7 @@ class EntryCategories:
if system in self._system_runs:
system_cores, unresolved = self._system_runs[system]
else:
system_cores = self._by_system.get(_norm_system_id(system), [])
system_cores = self._by_system.get(norm_system_id(system), [])
unresolved = self._unresolved
# A reader that runs the entry's system comes first and says so: a
# core of another system may only share the file's name.
+8 -8
View File
@@ -9,10 +9,10 @@ from dataclasses import dataclass, field
from core.hashing import compute_hashes, parse_md5_list
from core.ziptools import check_inside_zip
from resolve.localfile import resolve_local_file, variant_base_name
from resolve.packfiles import _records_by_path, preferred_entries
from resolve.packfiles import records_by_path, preferred_entries
def _normalize(destination: str, fold: bool = True) -> str:
def comparable_destination(destination: str, fold: bool = True) -> str:
"""Comparable form of a destination, since layers write it differently.
Case is folded only where the platform's filesystem folds it: on Linux
@@ -66,7 +66,7 @@ def find_collisions(
continue
dest = entry.get("destination") or entry.get("name") or ""
if dest:
by_dest.setdefault(_normalize(dest, fold), []).append((sys_id, entry))
by_dest.setdefault(comparable_destination(dest, fold), []).append((sys_id, entry))
collisions = []
for key, claims in sorted(by_dest.items()):
@@ -90,7 +90,7 @@ def find_collisions(
# A file every declaration accepts settles the path: RetroDECK
# declares ATARIOSB.ROM twice, the second with an md5 list that
# also names the first one's file.
if any(_accepted_by_all(path, entries, db) for path in resolved):
if any(accepted_by_all(path, entries, db) for path in resolved):
continue
reached = sorted(
(sys_id, local)
@@ -112,7 +112,7 @@ def find_collisions(
return collisions
def _lists_hashes(entry: dict) -> bool:
def lists_hashes(entry: dict) -> bool:
"""Whether a declaration says anything about content at all."""
return any(
_declared_hashes(entry, field_name)
@@ -142,10 +142,10 @@ def _record_at(path: str, db: dict) -> dict | None:
path verify --all and slots.py both take. The index is the pack
resolver's, so one run holds one copy of it.
"""
return _records_by_path(db).get(path)
return records_by_path(db).get(path)
def _content_sha1(path: str, db: dict) -> str | None:
def content_sha1(path: str, db: dict) -> str | None:
"""The sha1 of the file at path, from the database or read from disk.
A data directory cache is not in the database, so its files are hashed.
@@ -158,7 +158,7 @@ def _content_sha1(path: str, db: dict) -> str | None:
return compute_hashes(path, frozenset({"sha1"}))["sha1"]
def _accepted_by_all(path: str, entries: list[dict], db: dict) -> bool:
def accepted_by_all(path: str, entries: list[dict], db: dict) -> bool:
"""Whether every declaration's own hashes accept the file at path."""
record = _record_at(path, db)
if record is None:
+15 -15
View File
@@ -14,7 +14,7 @@ from resolve.layout import (
CONTENT_TAG_PREFIXES,
OUTSIDE_BIOS_FOLDER,
ROM_SEARCH_PREFIX,
_placed_entry,
placed_entry,
standalone_layout_path,
)
from model.declarations import ROMS_ROOT, outer_layout
@@ -24,7 +24,7 @@ from core.paths import REPO_ROOT
LIBRETRO_RUNNERS = frozenset({"libretro", "retroarch", "retroarch32", "retrorun"})
def _core_key(name: str) -> str:
def core_key(name: str) -> str:
"""A core name as two platforms spell it alike: mame2003-plus, mame2003_plus."""
return str(name).lower().replace("-", "_")
@@ -83,9 +83,9 @@ def offer_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]:
for row in config.get("_rom_folders") or []:
folder = str(row.get("folder") or "")
offers = row.get("offers") or []
offered = {(o.get("emulator"), _core_key(o.get("core") or "")) for o in offers}
offered = {(o.get("emulator"), core_key(o.get("core") or "")) for o in offers}
choices: list[tuple[dict, set[str]]] = []
if row.get("core") and (row.get("emulator"), _core_key(row["core"])) not in offered:
if row.get("core") and (row.get("emulator"), core_key(row["core"])) not in offered:
choices.append((row, every))
for key, spec in (row.get("board_defaults") or {}).items():
branch = str(key).replace("=", " ", 1)
@@ -96,7 +96,7 @@ def offer_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]:
if when else every))
for choice, boards in choices:
if choice.get("core") and choice.get("emulator") in LIBRETRO_RUNNERS:
found.setdefault((_core_key(choice["core"]), folder), set()).update(boards)
found.setdefault((core_key(choice["core"]), folder), set()).update(boards)
return {
pair: None if not names or boards >= every else frozenset(boards)
for pair, boards in found.items()
@@ -108,10 +108,10 @@ def content_folder_boards(config: dict) -> dict[tuple[str, str], frozenset[str]
with the boards it does so on, None for every board."""
pairs: set[tuple[str, str]] = set()
for core, systems in (config.get("libretro_systems") or {}).items():
pairs |= {(_core_key(core), str(s)) for s in systems or []}
pairs |= {(core_key(core), str(s)) for s in systems or []}
for system in (config.get("systems") or {}).values():
if isinstance(system, dict) and system.get("native_id"):
pairs |= {(_core_key(c), str(system["native_id"])) for c in system.get("cores") or []}
pairs |= {(core_key(c), str(system["native_id"])) for c in system.get("cores") or []}
for record in config.get("launchers") or []:
if record.get("kind") == "package" and record.get("build") == "libretro":
package = str(record.get("emulator", ""))
@@ -120,7 +120,7 @@ def content_folder_boards(config: dict) -> dict[tuple[str, str], frozenset[str]
# drivers alone, none of the arcade sets of the core it
# shares a repository with.
continue
core = _core_key(package.removeprefix("lr-"))
core = core_key(package.removeprefix("lr-"))
pairs |= {(core, str(s)) for s in record.get("systems") or []}
# Pairs from the platform's own lists hold on every board, an offer on
# the boards its frontend writes it for.
@@ -156,10 +156,10 @@ def content_folder_tags(config: dict) -> set[str]:
boards = content_folder_boards(config)
target = config.get(TARGET_KEY)
pairs = {pair for pair, on in boards.items() if not target or on is None or target in on}
from resolve.launchers import _roms_place
from resolve.launchers import roms_place_of
def place(folder: str) -> list:
return list(_roms_place(config, folder) or ())
return list(roms_place_of(config, folder) or ())
# Without a board, a core a folder offers on some boards only carries
# them, for a manifest the installer narrows to one.
@@ -272,7 +272,7 @@ def _roms_entry(entry: dict, tree: str, folder: str, rel: str) -> dict:
"""The entry placed in a roms folder."""
# Below the roms root inside the install tree (EmuELEC's
# /storage/roms): a plain dest the platform prefix skips, as a
# standalone entry placed there (_placed_entry).
# standalone entry placed there (placed_entry).
where: dict[str, object] = (
{"unprefixed": True} if tree == "install" else {"root": ROMS_ROOT}
)
@@ -361,7 +361,7 @@ def _standalone_content_layout(emu_name: str, view: dict, searches: list) -> dic
out.append(f)
held = {(f.get("root") or "", f.get("standalone_path") or "")}
extra = [
_placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
]
extra = [e for e in extra if (e.get("root") or "", e["standalone_path"]) not in held]
changed |= bool(extra)
@@ -373,7 +373,7 @@ def _standalone_content_layout(emu_name: str, view: dict, searches: list) -> dic
changed = True
placed = {k: v for k, v in f.items() if k != "unplaced"}
out.extend(
_placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
)
return {**view, "files": out} if changed else view
@@ -403,13 +403,13 @@ def content_layout(
return {**view, "files": files}
if CONTENT_SCOPE_TAG not in tags:
return view
names = {_core_key(n) for n in {emu_name, *(str(c) for c in view.get("cores") or [])}}
names = {core_key(n) for n in {emu_name, *(str(c) for c in view.get("cores") or [])}}
searches = [
json.loads(t[len(ROM_SEARCH_PREFIX):])
for t in tags if t.startswith(ROM_SEARCH_PREFIX)
]
build = "standalone" if standalone else "libretro"
searches = [s for s in searches if _core_key(s[0]) in names and s[6] == build]
searches = [s for s in searches if core_key(s[0]) in names and s[6] == build]
if not standalone:
return _libretro_content_layout(emu_name, view, tags, names, searches)
return _standalone_content_layout(emu_name, view, searches)
+4 -4
View File
@@ -10,7 +10,7 @@ from core.cli import suggest_names
from core.paths import sanitize_pack_path
from model.platforms import load_platform_config
from model.profiles import preferred_profile, upstream_profile_index
from model.systems import _norm_system_id, select_systems
from model.systems import norm_system_id, select_systems
from model.targets import list_available_targets, load_target_config
from core.paths import REPO_ROOT
@@ -212,11 +212,11 @@ def _platform_profiles(
result |= every_libretro()
else:
# Fallback: system ID intersection with normalization
norm_plat_systems = {_norm_system_id(s) for s in config.get("systems", {})}
norm_plat_systems = {norm_system_id(s) for s in config.get("systems", {})}
result = {
name
for name, p in profiles.items()
if {_norm_system_id(s) for s in p.get("systems", [])} & norm_plat_systems
if {norm_system_id(s) for s in p.get("systems", [])} & norm_plat_systems
and p.get("type") != "alias"
and not p.get("built_by")
}
@@ -311,7 +311,7 @@ def system_core_reach(
None, kept whatever is available, there being no information to exclude
it.
"""
_norm_sid = _norm_system_id
_norm_sid = norm_system_id
# Normalized system -> cores, from ALL profiles
norm_system_cores: dict[str, set[str]] = {}
+2 -2
View File
@@ -9,7 +9,7 @@ from collections.abc import Callable
from resolve.content import adler32_fits, content_fits, name_match_size_ok
def _resolve_in_data_dirs(
def resolve_in_data_dirs(
names_to_try: list[str],
data_dir_registry: dict,
verdict: Callable[[str], str],
@@ -54,7 +54,7 @@ def _resolve_in_data_dirs(
return None, mismatch
def _data_dir_tail(
def data_dir_tail(
dest_hint: str, data_dir_registry: dict, file_entry: dict, db: dict
) -> str | None:
"""The cached data-directory file at the destination's own tail.
+8 -8
View File
@@ -205,7 +205,7 @@ def _bios_relative(directory: str, base: str) -> str | None:
return None if re.search(r"[\s<>]", relative) else relative
def _directories(record: dict, base: str) -> list[str] | None:
def record_directories(record: dict, base: str) -> list[str] | None:
"""The directories a record reads, in order. None when the code says none.
``search_dir`` transcribes the code, conditions included: "bios/chihiro,
@@ -230,7 +230,7 @@ def _directories(record: dict, base: str) -> list[str] | None:
return found
def _names(record: dict) -> list[str]:
def record_names(record: dict) -> list[str]:
"""The file names a record tries, placeholders expanded in code order."""
expands = record.get("expands") or {}
names: list[str] = []
@@ -591,8 +591,8 @@ def launcher_places(
kind = record.get("kind")
if kind not in PLACE_KINDS:
continue
names = _names(record)
directories = _directories(record, base)
names = record_names(record)
directories = record_directories(record, base)
if not names or directories == []:
continue
anchored = directories is not None
@@ -869,7 +869,7 @@ def handed_directories(
handles=handles,
source_ref=str(record.get("source_ref", "")),
roms_place=None if folder is not None else (
_roms_place(config, folder_in_roms(part, config))
roms_place_of(config, folder_in_roms(part, config))
or _configs_place(folder_in_configs(part, config))
or _emulators_place(folder_in_emulators(part, config))
),
@@ -893,7 +893,7 @@ def _emulators_place(path: str | None) -> Place | None:
return None if path is None else (EMULATORS_TREE, path)
def _roms_place(config: dict, path: str | None) -> Place | None:
def roms_place_of(config: dict, path: str | None) -> Place | None:
"""A path below the roms root as a place: in the install tree when the
platform installs above its BIOS folder (AmberELEC), else the roms tree."""
if path is None:
@@ -984,7 +984,7 @@ def executed_files(config: dict) -> list[ExecutedFile]:
if str(record.get("passes_to") or "").strip() != "exec":
continue
raw = str(record.get("search_dir") or "").strip()
directories = _directories(record, base)
directories = record_directories(record, base)
roms = folder_in_roms(raw, config) if raw and not directories else None
emulator_folder = folder_in_emulators(raw, config) if raw and not directories else None
# A program file needs no extension (pico8, vox): the names are
@@ -997,7 +997,7 @@ def executed_files(config: dict) -> list[ExecutedFile]:
f"{directories[0]}/{name}" if directories[0] else name
))
elif roms is not None:
place = _roms_place(config, sanitize_pack_path(f"{roms}/{name}" if roms else name))
place = roms_place_of(config, sanitize_pack_path(f"{roms}/{name}" if roms else name))
elif emulator_folder is not None:
place = (EMULATORS_TREE, sanitize_pack_path(f"{emulator_folder}/{name}"))
else:
+3 -3
View File
@@ -127,7 +127,7 @@ def system_dir_path(entry: dict, path: str) -> str:
return f"{directory}/{path}" if directory else path
def _handed(standalone_cores: Iterable[str]) -> list:
def handed_from_tags(standalone_cores: Iterable[str]) -> list:
"""The directories a standalone set carries, as launchers built them."""
from resolve.launchers import HandedDirectory
@@ -245,12 +245,12 @@ def standalone_bindings_for(
if isinstance(f, dict) and (path := standalone_layout_path(f, profile))
]
return standalone_bindings(
names, declared, _handed(standalone_cores), _executed(standalone_cores), layout,
names, declared, handed_from_tags(standalone_cores), _executed(standalone_cores), layout,
pools, systems,
)
def _placed_entry(entry: dict, profile: dict, placed: tuple[str, str]) -> dict:
def placed_entry(entry: dict, profile: dict, placed: tuple[str, str]) -> dict:
"""A standalone entry moved to the (tree, path) a platform reads it from."""
tree, path = placed
moved = {**entry, "standalone_path": path,
+38 -38
View File
@@ -15,9 +15,9 @@ from core.ziptools import check_inside_zip
from model.database import get_mame_clone_map
from model.profiles import CONTENT_CHECKS
from resolve.archives import (
_covering_archives,
_holding_members,
_warn_unreadable_archive,
covering_archives,
holding_members,
warn_unreadable_archive,
contents_members,
)
from resolve.content import (
@@ -28,14 +28,14 @@ from resolve.content import (
name_match_size_ok,
shape_fits,
)
from resolve.datadirs import _data_dir_tail, _resolve_in_data_dirs
from resolve.datadirs import data_dir_tail, resolve_in_data_dirs
from resolve.ownership import (
_affinity_tokens,
_engine_tree,
_foreign_tree,
_maker_folder,
_own_tree,
_owner_tokens,
affinity_tokens,
engine_tree,
foreign_tree,
maker_folder,
own_tree,
owner_tokens,
other_maker,
system_makers,
)
@@ -145,7 +145,7 @@ def _rank_tail_candidates(
candidates = [
h for h in candidates
if not path_of(h).endswith("/" + tail)
or not _foreign_tree(path_of(h), owners if start else set(asker))
or not foreign_tree(path_of(h), owners if start else set(asker))
]
if len(candidates) < 2:
return candidates
@@ -154,8 +154,8 @@ def _rank_tail_candidates(
candidates,
key=lambda h: (
len(path_of(h).split("/")) - depth,
not owners & _affinity_tokens(path_of(h).rsplit("/", 1)[0]),
_foreign_tree(path_of(h), owners),
not owners & affinity_tokens(path_of(h).rsplit("/", 1)[0]),
foreign_tree(path_of(h), owners),
),
)
@@ -174,15 +174,15 @@ def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str
if len(paths) < 2:
return paths
hint = dest_hint or file_entry.get("path") or file_entry.get("destination") or ""
wanted = _affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "")
owners = _owner_tokens(file_entry)
wanted = affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "")
owners = owner_tokens(file_entry)
sized = declares_shape(file_entry)
def score(path: str) -> tuple[int, bool, bool, bool, int]:
fits = 0
if sized and os.path.exists(path):
fits = int(shape_fits(file_entry, path))
tokens = _affinity_tokens(path.rsplit("/", 1)[0])
tokens = affinity_tokens(path.rsplit("/", 1)[0])
# The owner's own copy ranks above any shared tree segment: NetherSX2's
# shaders/common/ beat armsx2's own fxaa.fx on two directory tokens.
# Another emulator's own tree ranks below everything else.
@@ -191,8 +191,8 @@ def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str
# flycast-dojo, lindbergh-loader and vvvvvv took C-Dogs' 98-line
# gamecontrollerdb.txt by index order.
return (
fits, bool(owners & tokens), not _foreign_tree(path, owners | wanted),
not _engine_tree(path, owners | wanted), len(wanted & tokens),
fits, bool(owners & tokens), not foreign_tree(path, owners | wanted),
not engine_tree(path, owners | wanted), len(wanted & tokens),
)
return sorted(paths, key=score, reverse=True)
@@ -424,7 +424,7 @@ def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> lis
"""The records a destination tail names, ranked, ambiguity read."""
candidates = _rank_tail_candidates(
q.by_path_suffix.get(tail, []), start, tail, q.files_db, owners,
frozenset(_owner_tokens(q.file_entry)),
frozenset(owner_tokens(q.file_entry)),
)
raw = q.by_path_suffix.get(tail, [])
if start and len(raw) > 1:
@@ -436,7 +436,7 @@ def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> lis
# tree still answers a tail several files share.
candidates = [
h for h in candidates
if _own_tree(q.files_db.get(h, {}).get("path", ""), owners)
if own_tree(q.files_db.get(h, {}).get("path", ""), owners)
]
return candidates
@@ -490,7 +490,7 @@ def _by_path_suffix(q: _Lookup) -> tuple[Resolution | None, bool]:
hint_parts = q.dest_hint.split("/")
# The asking profile and the destination's own directories both name
# whose tree a copy may come from.
owners = _owner_tokens(q.file_entry) | _affinity_tokens("/".join(hint_parts[:-1]))
owners = owner_tokens(q.file_entry) | affinity_tokens("/".join(hint_parts[:-1]))
for start in range(min(2, len(hint_parts) - 1)):
candidates = _tail_candidates(q, start, "/".join(hint_parts[start:]), owners)
if start and len(candidates) > 1:
@@ -526,9 +526,9 @@ def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution
tail_hint
and data_dir_registry
and not q.has_strong_hash
and not _owner_tokens(q.file_entry)
and not owner_tokens(q.file_entry)
):
hit = _data_dir_tail(tail_hint, data_dir_registry, q.file_entry, q.db)
hit = data_dir_tail(tail_hint, data_dir_registry, q.file_entry, q.db)
if hit:
return hit, "path_exact"
return None
@@ -609,7 +609,7 @@ def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str]
for match_sha1 in folded.get(try_name.casefold(), []):
if match_sha1 in q.files_db and _name_size_ok(q, match_sha1):
path = q.files_db[match_sha1]["path"]
if _foreign_tree(path, owners):
if foreign_tree(path, owners):
continue
if os.path.exists(path) and path not in candidates:
candidates.append(path)
@@ -630,7 +630,7 @@ def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> li
for match_sha1 in shadowed.get(try_name, []):
path = q.files_db.get(match_sha1, {}).get("path", "")
if (
_maker_folder(path, str(q.db.get("bios_dir") or "bios"))
maker_folder(path, str(q.db.get("bios_dir") or "bios"))
in makers
and _name_size_ok(q, match_sha1)
and os.path.exists(path)
@@ -656,19 +656,19 @@ def _choose_by_name(
# Demul's naomi.zip holds more NAOMI BIOS rows than any MAME
# set and broke the superset the MAME cores were served.
candidates = [
p for p in candidates if not _foreign_tree(p, owners)
p for p in candidates if not foreign_tree(p, owners)
] or candidates
if members:
candidates = _holding_members(candidates, members)
candidates = holding_members(candidates, members)
elif len(candidates) > 1 and q.name.casefold().endswith(".zip"):
candidates = _covering_archives(candidates)
candidates = covering_archives(candidates)
candidates = _by_affinity(candidates, q.file_entry, q.dest_hint)
best = candidates[0] if candidates else ""
# A copy outside another emulator's tree comes first: the
# affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served
# upstream PCSX2 the patches.zip of ARMSX2.
candidates = [
p for p in candidates if not _foreign_tree(p, owners)
p for p in candidates if not foreign_tree(p, owners)
] or candidates
primary = [p for p in candidates if "/.variants/" not in p]
if not (primary or candidates):
@@ -682,8 +682,8 @@ def _choose_by_name(
# 8 KB copy was set aside, while data/bluemsx held its own,
# and MSX2P.ROM of another dump once only msx-emu answered
# the exact casing.
if data_dir_registry and (exact_foreign or _foreign_tree(best, owners)):
hit, _mismatch = _resolve_in_data_dirs(
if data_dir_registry and (exact_foreign or foreign_tree(best, owners)):
hit, _mismatch = resolve_in_data_dirs(
q.names_to_try, data_dir_registry,
functools.partial(
declared_hash_verdict,
@@ -714,11 +714,11 @@ def _by_name(
candidates = _exact_name_candidates(q)
if candidates and all("/.variants/" in p for p in candidates):
_add_variant_primaries(q, candidates)
owners = _owner_tokens(q.file_entry)
owners = owner_tokens(q.file_entry)
# Only another emulator's tree answers the exact casing: what it
# holds there says nothing about this entry's file.
exact_foreign = bool(candidates) and all(
_foreign_tree(p, owners) for p in candidates
foreign_tree(p, owners) for p in candidates
)
if not candidates or exact_foreign:
_add_casefold_candidates(q, candidates, owners)
@@ -730,13 +730,13 @@ def _by_name(
core_owners = {
token
for core in q.file_entry.get("platform_cores") or ()
for token in _affinity_tokens(str(core))
for token in affinity_tokens(str(core))
}
if (
not owners
and core_owners
and candidates
and all(_foreign_tree(p, core_owners) for p in candidates)
and all(foreign_tree(p, core_owners) for p in candidates)
):
return None, True
if makers and candidates:
@@ -803,7 +803,7 @@ def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Re
):
return path, "md5_composite_exact"
except (zipfile.BadZipFile, OSError) as exc:
_warn_unreadable_archive(path, exc)
warn_unreadable_archive(path, exc)
if db_md5.lower() in md5_set and not q.composite_only:
return path, "md5_exact"
return None
@@ -821,7 +821,7 @@ def _zipped_named(
if zipped_file.casefold() in inner_names:
valid.append((path, m, size))
except (zipfile.BadZipFile, OSError) as exc:
_warn_unreadable_archive(path, exc)
warn_unreadable_archive(path, exc)
# The archive whose member carries the declared md5 is the one:
# neogeo.zip is held twice, each with its own sfix.sfix, and the
# first by name was returned as a mismatch while the other matched.
@@ -909,7 +909,7 @@ def _in_data_dirs(q: _Lookup, data_dir_registry: dict) -> tuple[Resolution | Non
file_entry=q.file_entry,
db=q.db,
)
return _resolve_in_data_dirs(q.names_to_try, data_dir_registry, verdict)
return resolve_in_data_dirs(q.names_to_try, data_dir_registry, verdict)
def _resolve_layout(
+13 -13
View File
@@ -16,7 +16,7 @@ def names_manufacturer(sys_id: str, manufacturer: str) -> bool:
return sys_id == slug or sys_id.startswith(f"{slug}-")
def _maker_folder(path: str, bios_dir: str) -> str | None:
def maker_folder(path: str, bios_dir: str) -> str | None:
"""The bios/<maker>/ folder a collection path is filed under."""
prefix = f"{bios_dir.rstrip('/')}/"
if not path.startswith(prefix):
@@ -40,7 +40,7 @@ def _maker_folders(db: dict) -> frozenset[str]:
folders = frozenset(
folder
for entry in files_db.values()
if (folder := _maker_folder(str(entry.get("path", "")), bios_dir))
if (folder := maker_folder(str(entry.get("path", "")), bios_dir))
and folder not in BUCKET_FOLDERS
)
_maker_folders_cache[:] = [(files_db, len(files_db), folders)]
@@ -55,7 +55,7 @@ def system_makers(file_entry: dict, db: dict) -> frozenset[str]:
(pc88, arcade), so nothing is narrowed there.
"""
sys_id = str(file_entry.get("platform_system") or "")
if not sys_id or _owner_tokens(file_entry):
if not sys_id or owner_tokens(file_entry):
return frozenset()
return frozenset(
folder for folder in _maker_folders(db) if names_manufacturer(sys_id, folder)
@@ -66,11 +66,11 @@ def other_maker(path: str, makers: frozenset[str], db: dict) -> bool:
"""Whether a path is filed under a maker the entry's system does not name."""
if not makers:
return False
folder = _maker_folder(path, str(db.get("bios_dir") or "bios"))
folder = maker_folder(path, str(db.get("bios_dir") or "bios"))
return folder is not None and folder not in BUCKET_FOLDERS and folder not in makers
def _affinity_tokens(text: str) -> set[str]:
def affinity_tokens(text: str) -> set[str]:
return {
token
for token in (re.sub(r"[^0-9a-z]", "", part.casefold()) for part in text.split("/"))
@@ -78,7 +78,7 @@ def _affinity_tokens(text: str) -> set[str]:
}
def _owner_tokens(file_entry: dict) -> set[str]:
def owner_tokens(file_entry: dict) -> set[str]:
"""Tokens naming the profile that asks for the file.
A profile named after another with a suffix (cxbx-reloaded-2023,
@@ -90,14 +90,14 @@ def _owner_tokens(file_entry: dict) -> set[str]:
tokens: set[str] = set()
for owner in (file_entry.get("source_profile"), file_entry.get("source_emulator")):
if owner:
tokens |= _affinity_tokens(str(owner).replace(" ", ""))
tokens |= affinity_tokens(str(owner).replace(" ", ""))
profile = str(file_entry.get("source_profile") or "").casefold()
words = [word for word in re.split(r"[^0-9a-z]+", profile) if word]
tokens |= {"".join(words[:end]) for end in range(1, len(words))}
return tokens
def _foreign_tree(path: str, owners: set[str]) -> bool:
def foreign_tree(path: str, owners: set[str]) -> bool:
"""Whether a path lives in the tree of an emulator that is not the asker.
bios/Other/<emulator>/ holds what one emulator ships. A same-named file
@@ -108,20 +108,20 @@ def _foreign_tree(path: str, owners: set[str]) -> bool:
parts = path.split("/")
if not owners or len(parts) < 4 or parts[0] != "bios" or parts[1] != "Other":
return False
return not (owners & _affinity_tokens(parts[2]))
return not (owners & affinity_tokens(parts[2]))
def _engine_tree(path: str, owners: set[str]) -> bool:
def engine_tree(path: str, owners: set[str]) -> bool:
"""Whether a path lives in another game's folder under bios/Game Engines/."""
parts = path.split("/")
if len(parts) < 4 or parts[0] != "bios" or parts[1] != "Game Engines":
return False
return not (owners & _affinity_tokens(parts[2]))
return not (owners & affinity_tokens(parts[2]))
def _own_tree(path: str, owners: set[str]) -> bool:
def own_tree(path: str, owners: set[str]) -> bool:
"""Whether a path lives in the bios/Other/<emulator>/ tree of the asker."""
parts = path.split("/")
if not owners or len(parts) < 4 or parts[0] != "bios" or parts[1] != "Other":
return False
return bool(owners & _affinity_tokens(parts[2]))
return bool(owners & affinity_tokens(parts[2]))
+8 -8
View File
@@ -21,13 +21,13 @@ from core.paths import REPO_ROOT, declared_destination
from resolve.validation import inner_rom_check
# CLI-wide network policy. Public helpers can override it explicitly, while
# every CLI mode inherits --offline (including large-file release fallback).
_OFFLINE = False
OFFLINE = False
def set_offline(value: bool) -> None:
"""Forbid every network reach for the rest of the run."""
global _OFFLINE
_OFFLINE = value
global OFFLINE
OFFLINE = value
def scratch_dir() -> str:
@@ -61,7 +61,7 @@ def download_external(
if declared is None:
print(f" WARNING: no hash for {name}, skipping unverifiable download")
return False
if _OFFLINE if offline is None else offline:
if OFFLINE if offline is None else offline:
print(f" WARNING: {name} is external and the run is offline, not fetched")
return False
algo, expected = declared
@@ -140,7 +140,7 @@ def _verified_asset(
def run_is_offline(offline: bool | None = None) -> bool:
"""Whether this run fetches nothing: --offline, or RETROBIOS_OFFLINE."""
return bool(
(_OFFLINE if offline is None else offline)
(OFFLINE if offline is None else offline)
or os.environ.get("RETROBIOS_OFFLINE")
)
@@ -148,7 +148,7 @@ def run_is_offline(offline: bool | None = None) -> bool:
_RECORDS_BY_PATH: list[tuple[dict, int, dict[str, dict]]] = []
def _records_by_path(db: dict) -> dict[str, dict]:
def records_by_path(db: dict) -> dict[str, dict]:
"""The database records by path, built once per database."""
files = db.get("files", {})
if _RECORDS_BY_PATH:
@@ -185,7 +185,7 @@ def pending_release_asset(
assets = set(asset_candidates(name, registered))
if not assets:
return None
records = _records_by_path(db)
records = records_by_path(db)
declared_size = file_entry.get("size")
for path, asset in sorted(asset_names(registered).items()):
record = records.get(path)
@@ -396,7 +396,7 @@ def resolve_file(
# exactly what the flag forbids.
return (path, status) if path else (None, "not_found")
cached = _verified_asset(
name, declared, file_entry, _OFFLINE if offline is None else offline,
name, declared, file_entry, OFFLINE if offline is None else offline,
)
if cached:
return cached, "release_asset"
+26 -26
View File
@@ -17,13 +17,13 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from model.systems import _norm_system_id
from model.systems import norm_system_id
from core.paths import REPO_ROOT
HASH_FIELDS = ("sha1", "md5", "sha256", "crc32")
def _hash_values(entry: dict, field_name: str) -> list[str]:
def hash_values(entry: dict, field_name: str) -> list[str]:
"""Return a hash field as a list, whatever shape it was written in."""
raw = entry.get(field_name)
if not raw:
@@ -62,8 +62,8 @@ def checked_hashes(entry: dict | None) -> dict | None:
kinds = {str(k) for k in raw}
else:
kinds = {str(raw)}
checked = [f for f in HASH_FIELDS if f in kinds and _hash_values(entry, f)]
if checked and all(len(set(_hash_values(entry, f))) == 1 for f in checked):
checked = [f for f in HASH_FIELDS if f in kinds and hash_values(entry, f)]
if checked and all(len(set(hash_values(entry, f))) == 1 for f in checked):
return entry
return {k: v for k, v in entry.items() if k not in HASH_FIELDS or k in kinds}
@@ -96,8 +96,8 @@ def contradicted_hashes(truth_entry: dict, platform_entry: dict | None) -> list[
theirs = comparable(platform_entry)
return [
field_name for field_name in HASH_FIELDS
if (ours := set(_hash_values(checked, field_name)))
and (held := set(_hash_values(theirs, field_name)))
if (ours := set(hash_values(checked, field_name)))
and (held := set(hash_values(theirs, field_name)))
and not ours & held
]
@@ -111,15 +111,15 @@ def is_label(entry: dict) -> bool:
return bool(entry.get("_cores")) and "_named_by" in entry and not entry["_named_by"]
def _is_placeholder(name: str) -> bool:
def is_placeholder(name: str) -> bool:
return "<" in name or ">" in name or "*" in name
def _field_sets(entry: dict | None) -> dict[str, set[str]]:
return {f: set(_hash_values(entry or {}, f)) for f in HASH_FIELDS}
return {f: set(hash_values(entry or {}, f)) for f in HASH_FIELDS}
def _single_size(value: int | str | list[int | str]) -> int | None:
def single_size(value: int | str | list[int | str]) -> int | None:
"""One size, or None: a list names several accepted revisions, which a
single size field cannot state (int() on it stopped the whole export)."""
if isinstance(value, list):
@@ -206,9 +206,9 @@ class NativeFile:
rejects a file will reject it whatever the platform declares.
"""
if field_name == "md5" and self.composite_md5:
return _hash_values(self.platform or {}, field_name)
truth_values = _hash_values(self._checked_truth, field_name)
platform_values = _hash_values(self.platform or {}, field_name)
return hash_values(self.platform or {}, field_name)
truth_values = hash_values(self._checked_truth, field_name)
platform_values = hash_values(self.platform or {}, field_name)
source = self._identity_source()
if source == "platform":
return platform_values
@@ -242,11 +242,11 @@ class NativeFile:
is written when it names one value, which is then that dump's.
"""
if field_name == "md5" and self.composite_md5:
values = _hash_values(self.platform or {}, field_name)
values = hash_values(self.platform or {}, field_name)
return values[0] if values else ""
source = self._identity_source()
truth_values = _hash_values(self._checked_truth, field_name)
platform_values = _hash_values(self.platform or {}, field_name)
truth_values = hash_values(self._checked_truth, field_name)
platform_values = hash_values(self.platform or {}, field_name)
if source == "truth":
return truth_values[0] if truth_values else ""
if source == "platform" or not truth_values:
@@ -305,7 +305,7 @@ class NativeFile:
for entry in order:
if not entry or not entry.get("size"):
continue
single = _single_size(entry["size"])
single = single_size(entry["size"])
if single is None:
if accepted is None:
accepted = {int(v) for v in entry["size"]}
@@ -425,19 +425,19 @@ def by_name(truth_entry: dict, platform_entry: dict) -> bool:
def by_hash(truth_entry: dict, platform_entry: dict) -> bool:
"""A value on any of the four hash fields in common: a renamed file."""
ours = {v for f in HASH_FIELDS for v in _hash_values(truth_entry, f)}
ours = {v for f in HASH_FIELDS for v in hash_values(truth_entry, f)}
if not ours:
return False
theirs = comparable(platform_entry)
return bool(ours & {v for f in HASH_FIELDS for v in _hash_values(theirs, f)})
return bool(ours & {v for f in HASH_FIELDS for v in hash_values(theirs, f)})
def _contradicts(truth_entry: dict, platform_entry: dict) -> bool:
"""A hash both entries declare, without a value in common."""
platform_entry = comparable(platform_entry)
return any(
(ours := set(_hash_values(truth_entry, f)))
and (theirs := set(_hash_values(platform_entry, f)))
(ours := set(hash_values(truth_entry, f)))
and (theirs := set(hash_values(platform_entry, f)))
and not ours & theirs
for f in HASH_FIELDS
)
@@ -541,7 +541,7 @@ def _correct_matched(matched: NativeFile, truth_entry: dict, report: Report) ->
report.hashes_corrected.append(
f"{matched.native_system}/{matched.name} {field_name}"
)
elif _hash_values(checked, field_name) and not _hash_values(
elif hash_values(checked, field_name) and not hash_values(
comparable(matched.platform), field_name
):
matched.filled.append(field_name)
@@ -581,7 +581,7 @@ class _TruthPass:
def __post_init__(self) -> None:
scraped_systems = self.scraped_systems
self.norm_to_scraped = {
_norm_system_id(key): key for key in scraped_systems
norm_system_id(key): key for key in scraped_systems
}
self.platform_ids = {
native_id
@@ -593,7 +593,7 @@ class _TruthPass:
}
self.native_by_norm = {}
for system in self.systems.values():
self.native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id)
self.native_by_norm.setdefault(norm_system_id(system.native_id), system.native_id)
def target_native_ids(self, truth_sid: str) -> tuple[list[str], bool]:
"""The native ids a truth system spans, and whether the first one
@@ -601,7 +601,7 @@ class _TruthPass:
scraped_systems = self.scraped_systems
scraped_key = truth_sid if truth_sid in scraped_systems else None
if scraped_key is None:
scraped_key = self.norm_to_scraped.get(_norm_system_id(truth_sid))
scraped_key = self.norm_to_scraped.get(norm_system_id(truth_sid))
if scraped_key is not None:
sys_data = scraped_systems[scraped_key]
ids = {
@@ -620,7 +620,7 @@ class _TruthPass:
ordered.remove(primary)
ordered.insert(0, primary)
return ordered, primary in ids or len(ordered) == 1
direct = self.native_by_norm.get(_norm_system_id(truth_sid))
direct = self.native_by_norm.get(norm_system_id(truth_sid))
return ([direct] if direct else [truth_sid]), True
def _files_of(self, target_ids: list[str]) -> list[NativeFile]:
@@ -639,7 +639,7 @@ class _TruthPass:
truth_files = [
entry for entry in truth_files
if (name := str(entry.get("name", "")))
and not name.startswith("_") and not _is_placeholder(name)
and not name.startswith("_") and not is_placeholder(name)
]
candidates = [c for c in self._files_of(target_ids) if c.truth is None]
pairs = pair_entries(truth_files, [c.platform or {} for c in candidates])
+2 -2
View File
@@ -16,7 +16,7 @@ except ImportError:
yaml = None
from core.hashing import compute_hashes, parse_hash_list, parse_md5_list, stream_hashes
from model.nodedup import _in_nodedup_dir
from model.nodedup import in_nodedup_dir
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from model.registry import list_registered_platforms
@@ -467,7 +467,7 @@ def _check_duplicate(result: ValidationResult, db: dict, relative: str) -> None:
# PR that regenerated database.json was told each new file
# duplicated itself.
result.add_check(True, "Already in the database at this path")
elif _in_nodedup_dir(relative):
elif in_nodedup_dir(relative):
result.add_info(
f"Identical to `{existing['path']}`, kept: this tree is read by path"
)
+8 -8
View File
@@ -8,7 +8,7 @@ from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from model.profiles import load_emulator_profiles
from model.systems import _norm_system_id
from model.systems import norm_system_id
from resolve.contentlayout import content_folder_tags, content_layout
from resolve.layout import (
CONTENT_TAG_PREFIXES,
@@ -20,8 +20,8 @@ from resolve.layout import (
OUTSIDE_BIOS_FOLDER,
OWN_BUILD_PREFIX,
SYSTEM_FILE_PREFIX,
_handed,
_placed_entry,
handed_from_tags,
placed_entry,
core_system_dirs,
entry_launch_systems,
runs_standalone,
@@ -131,7 +131,7 @@ def standalone_set(config: dict) -> set[str]:
natives = native_systems(config)
names |= {
SYSTEM_FILE_PREFIX + json.dumps(
[natives.get(str(native), str(native)), MACHINE_KEY + _norm_system_id(str(m))]
[natives.get(str(native), str(native)), MACHINE_KEY + norm_system_id(str(m))]
)
for record in config.get("launchers") or []
for native in record.get("systems") or []
@@ -196,7 +196,7 @@ class _StandaloneLaunches:
names = {emu_name, *(str(c) for c in profile.get("cores") or [])}
per_system = bool(
profile.get("standalone_directories") or profile.get("standalone_pools")
) and any(h.systems and h.emulator in names for h in _handed(standalone_cores))
) and any(h.systems and h.emulator in names for h in handed_from_tags(standalone_cores))
index = system_file_index(standalone_cores) if per_system else {}
# A profile system the platform launches under a system of its own, as
# its list says for one entry, is launched there for every entry:
@@ -212,7 +212,7 @@ class _StandaloneLaunches:
# the folder its record gives, every other launch the folder the records
# naming none give.
named_systems = frozenset().union(*(
h.systems for h in _handed(standalone_cores) if h.emulator in names
h.systems for h in handed_from_tags(standalone_cores) if h.emulator in names
)) if per_system else frozenset()
# The layout folders a search setting stands for (standalone_pools):
@@ -237,7 +237,7 @@ class _StandaloneLaunches:
# own system selects the launch that offers it as a machine
# (RetroBat runs XRoar's coco3 under coco).
systems = systems.union(*(
self.index.get(MACHINE_KEY + _norm_system_id(s), set()) for s in own
self.index.get(MACHINE_KEY + norm_system_id(s), set()) for s in own
))
return systems
@@ -298,7 +298,7 @@ class _StandaloneLaunches:
# -hash bios/mame/hash (Mame64.Generator.cs:172, 177-178), and
# the hash/ beside mame.exe is no longer read.
moved = {k: v for k, v in f.items() if k != "bundled"}
files.extend(_placed_entry(moved, self.profile, placed) for placed in places)
files.extend(placed_entry(moved, self.profile, placed) for placed in places)
return files
+8 -8
View File
@@ -12,7 +12,7 @@ import sys
from dataclasses import dataclass
from model.declarations import OUTER_ROOTS
from model.systems import _norm_system_id
from model.systems import norm_system_id
from model.registry import load_data_dir_registry
from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set
from resolve.cores import resolve_platform_cores
@@ -676,7 +676,7 @@ class _SystemMap:
declared_by_name.setdefault(fname, []).append((psid, fe))
norm_to_platform: dict[str, str] = {}
for psid in config.get("systems", {}):
norm_to_platform.setdefault(_norm_system_id(psid), psid)
norm_to_platform.setdefault(norm_system_id(psid), psid)
return cls(
set(config.get("systems", {}).keys()), declared_by_name, norm_to_platform, db,
)
@@ -685,7 +685,7 @@ class _SystemMap:
"""Map a profile system ID to the platform's system ID."""
if profile_sid in self.platform_sys_ids:
return profile_sid
return self.norm_to_platform.get(_norm_system_id(profile_sid), profile_sid)
return self.norm_to_platform.get(norm_system_id(profile_sid), profile_sid)
def attribute(self, fe: dict, own: str | None, on_platform: set[str]) -> list[str]:
"""The platform systems an entry belongs to, [] when nothing decides.
@@ -962,12 +962,12 @@ def _diff_system(truth_sys: dict, scraped_sys: dict) -> dict:
correct while the export corrected hashes the diff never named. An entry
never answers for two.
"""
from resolve.reconcile import _is_placeholder, is_label, pair_entries, platform_declares
from resolve.reconcile import is_placeholder, is_label, pair_entries, platform_declares
truth_files = [
fe for fe in truth_sys.get("files", [])
if fe.get("name") and not fe["name"].startswith("_")
and not _is_placeholder(fe["name"])
and not is_placeholder(fe["name"])
]
scraped_files = scraped_sys.get("files", [])
@@ -1074,7 +1074,7 @@ def _update_summary(summary: dict, sys_div: dict) -> None:
def diff_platform_truth(truth: dict, scraped: dict) -> dict:
"""Compare truth YAML against scraped YAML, returning divergences.
System IDs are matched using normalized forms (via _norm_system_id) to
System IDs are matched using normalized forms (via norm_system_id) to
handle naming differences between emulator profiles and scraped platforms
(e.g. 'sega-game-gear' vs 'sega-gamegear').
"""
@@ -1099,13 +1099,13 @@ def diff_platform_truth(truth: dict, scraped: dict) -> dict:
# Build normalized-ID lookup for truth systems
norm_to_truth: dict[str, str] = {}
for sid in truth_systems:
norm_to_truth[_norm_system_id(sid)] = sid
norm_to_truth[norm_system_id(sid)] = sid
# Match scraped systems to truth via normalized IDs
matched_truth: set[str] = set()
for s_sid in sorted(scraped_systems):
norm = _norm_system_id(s_sid)
norm = norm_system_id(s_sid)
t_sid = norm_to_truth.get(norm)
if t_sid is None:
+3 -3
View File
@@ -50,7 +50,7 @@ _CONTENT_REASONS = {
_HASH_CHECKS = frozenset({"crc32", "md5", "sha1", "adler32"})
def _parse_validation(validation: list | dict | None) -> list[str]:
def parse_validation(validation: list | dict | None) -> list[str]:
"""Extract the validation check list from a file's validation field.
Handles both simple list and divergent (core/upstream) dict forms.
@@ -378,7 +378,7 @@ def _index_entry(index: dict[str, dict], emu_name: str, f: dict, checks: list[st
_merge_per_emulator(item, emu_name, f, checks)
def _build_validation_index(profiles: dict) -> dict[str, dict]:
def build_validation_index(profiles: dict) -> dict[str, dict]:
"""Build per-filename validation rules from emulator profiles.
Returns {filename: {"checks": [str], "size": int|None, "min_size": int|None,
@@ -407,7 +407,7 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]:
fname = f.get("name", "")
if not fname:
continue
checks = _parse_validation(f.get("validation"))
checks = parse_validation(f.get("validation"))
slot = (fname, emu_name, f.get("path") or fname)
if not checks:
unchecked.add(slot)
+3 -3
View File
@@ -11,7 +11,7 @@ from core.hashing import compute_hashes
from core.paths import REPO_ROOT
from core.torrentzip import write_torrentzip, zlib_ng_version
from romrecipes.ledger import is_archive_path
from romrecipes.members import _member_sha1, _opener
from romrecipes.members import member_sha1, member_opener
# --- build ------------------------------------------------------------------
@@ -79,7 +79,7 @@ def _members_match(built: Path, members: list[dict]) -> str:
sizes = {info.filename: info.file_size for info in archive.infolist()}
crcs = {info.filename: f"{info.CRC:08x}" for info in archive.infolist()}
held = sorted(
(name, sizes[name], crcs[name], _member_sha1(built, name)) for name in names
(name, sizes[name], crcs[name], member_sha1(built, name)) for name in names
)
if held == expected:
return ""
@@ -134,7 +134,7 @@ def build_archive(
with scratch.open("wb") as handle:
write_torrentzip(
handle,
[(name, _opener(source.path, source.member)) for name, source in sources],
[(name, member_opener(source.path, source.member)) for name, source in sources],
)
if exact:
written = compute_hashes(scratch, frozenset({"sha1"}), cache=False)["sha1"]
+3 -3
View File
@@ -13,7 +13,7 @@ from typing import BinaryIO
from core.hashing import parse_hash_list
from core.torrentzip import write_torrentzip, zlib_ng_version
from romrecipes.ledger import database_archives
from romrecipes.members import _member_sha1, _opener
from romrecipes.members import member_sha1, member_opener
from romrecipes.pins import container_entries
from romrecipes.romsets import collect_recipes, load_dat_recipes
@@ -65,14 +65,14 @@ def read_archive(path: Path, sha1: str) -> dict:
for _attempt in range(2):
sink = HashSink()
written = write_torrentzip(
sink, [(info.filename, _opener(path, info.filename)) for info in files]
sink, [(info.filename, member_opener(path, info.filename)) for info in files]
)
by_name = {member.name: member.sha1 for member in written}
if sink.sha1.hexdigest() == sha1:
rebuild = "exact"
break
else:
by_name = {info.filename: _member_sha1(path, info.filename) for info in files}
by_name = {info.filename: member_sha1(path, info.filename) for info in files}
record: dict = {
"rebuild": rebuild,
"members": [
+2 -2
View File
@@ -32,12 +32,12 @@ class _Member(io.RawIOBase):
super().close()
def _opener(source: Path, member: str | None) -> Callable[[], Readable]:
def member_opener(source: Path, member: str | None) -> Callable[[], Readable]:
if member is None:
return lambda: source.open("rb")
return lambda: _Member(source, member)
def _member_sha1(path: Path, name: str) -> str:
def member_sha1(path: Path, name: str) -> str:
with _Member(path, name) as stream:
return stream_hashes(stream, frozenset({"sha1"}))["sha1"]
+2 -2
View File
@@ -11,7 +11,7 @@ import urllib.parse
import urllib.request
from model.safeparse import yaml_load
from model.registry import _load_versions
from model.registry import load_versions
log = logging.getLogger(__name__)
@@ -76,7 +76,7 @@ def check(registry_path: str = DEFAULT_REGISTRY) -> dict:
return {"error": str(exc), "entries": []}
tracked = load_tracked_entries(registry_path)
versions = _load_versions()
versions = load_versions()
buildbot_set = set(index_zips)
tracked_set = set(tracked.keys())
+5 -5
View File
@@ -188,14 +188,14 @@ _RE_ARRAY = re.compile(
# checkBIOS.sh declares its checks as `checkPS1BIOS(){`, with no `function`
# keyword and no settled casing for BIOS.
_RE_FUNC = re.compile(
RE_FUNC = re.compile(
r"^[ \t]*(?:function\s+)?(check\w*(?:BIOS|Bios))\s*\(\)\s*\{",
re.MULTILINE,
)
# The hash list is named differently in each check (PSBios, hashes, ...), so
# it is found by shape rather than by name.
_RE_LOCAL_HASHES = re.compile(
RE_LOCAL_HASHES = re.compile(
r"(?:local\s+)?\w+=\(\s*((?:[0-9a-fA-F]{32}\s*)+)\)",
re.MULTILINE,
)
@@ -276,16 +276,16 @@ class Scraper(BaseScraper):
def _parse_function_hashes(self, script: str) -> dict[str, list[str]]:
"""Extract local hash arrays from named check functions."""
result: dict[str, list[str]] = {}
for func_match in _RE_FUNC.finditer(script):
for func_match in RE_FUNC.finditer(script):
func_name = func_match.group(1)
if func_name not in FUNCTION_HASH_MAP:
continue
system = FUNCTION_HASH_MAP[func_name]
func_start = func_match.start()
next_func = _RE_FUNC.search(script, func_match.end())
next_func = RE_FUNC.search(script, func_match.end())
func_end = next_func.start() if next_func else len(script)
func_body = script[func_start:func_end]
local_match = _RE_LOCAL_HASHES.search(func_body)
local_match = RE_LOCAL_HASHES.search(func_body)
if local_match:
hashes_raw = local_match.group(1)
hashes = [h.strip() for h in hashes_raw.split() if h.strip()]
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff. Show more