chore: lint and type the remaining tools

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 08:25:26 +01:00
1 parent 54521380dc
commit fe243ce8a8
11 files changed
+27 -31

No files matched your search

+1
View File
@@ -243,6 +243,7 @@ def step2_scan_branches(entry: dict) -> bytes | None:
["git", "ls-tree", "-r", "--name-only", ref], ["git", "ls-tree", "-r", "--name-only", ref],
capture_output=True, capture_output=True,
text=True, text=True,
check=False,
) )
for filepath in result.stdout.strip().split("\n"): for filepath in result.stdout.strip().split("\n"):
+1 -4
View File
@@ -102,10 +102,7 @@ def check(registry_path: str = DEFAULT_REGISTRY) -> dict:
buildbot_set = set(index_zips) buildbot_set = set(index_zips)
tracked_set = set(tracked.keys()) tracked_set = set(tracked.keys())
results: list[dict] = [] results: list[dict] = [{"zip": z, "status": "NEW", "key": None} for z in sorted(buildbot_set - tracked_set)]
for z in sorted(buildbot_set - tracked_set):
results.append({"zip": z, "status": "NEW", "key": None})
for z in sorted(tracked_set - buildbot_set): for z in sorted(tracked_set - buildbot_set):
key, _ = tracked[z] key, _ = tracked[z]
+4 -4
View File
@@ -40,7 +40,7 @@ import subprocess
import sys import sys
import tempfile import tempfile
import urllib.request import urllib.request
from collections.abc import Iterator from collections.abc import Container, Iterator
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict, dataclass, field from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone from datetime import datetime, timezone
@@ -585,7 +585,7 @@ def _platform_overrides(overrides: dict, platform: str) -> dict:
def unresolved_target_cores( def unresolved_target_cores(
targets: dict, index: dict[str, str], overrides: dict targets: dict, index: Container[str], overrides: dict
) -> dict[str, list[str]]: ) -> dict[str, list[str]]:
"""Core names a target ends up with that no profile claims. """Core names a target ends up with that no profile claims.
@@ -618,7 +618,7 @@ def check_targets(
) -> list[Finding]: ) -> list[Finding]:
targets_dir = platforms_dir / "targets" targets_dir = platforms_dir / "targets"
overrides_path = targets_dir / "_overrides.yml" overrides_path = targets_dir / "_overrides.yml"
overrides = {} overrides: dict = {}
if overrides_path.is_file(): if overrides_path.is_file():
with overrides_path.open(encoding="utf-8") as fh: with overrides_path.open(encoding="utf-8") as fh:
overrides = yaml_load(fh) or {} overrides = yaml_load(fh) or {}
@@ -1380,7 +1380,7 @@ def specifier_allows(spec: str, version: str) -> bool:
for clause in filter(None, (c.strip() for c in spec.split(","))): for clause in filter(None, (c.strip() for c in spec.split(","))):
match = _SPEC_CLAUSE.fullmatch(clause) match = _SPEC_CLAUSE.fullmatch(clause)
test = _SPEC_TESTS.get(match.group(1)) if match else None test = _SPEC_TESTS.get(match.group(1)) if match else None
if test is None or not test(target, _version_tuple(match.group(2))): if match is None or test is None or not test(target, _version_tuple(match.group(2))):
return False return False
return True return True
+4 -4
View File
@@ -23,14 +23,14 @@ def accepts(entry: dict, path: Path, mode: str) -> bool:
with zipfile.ZipFile(path) as archive: with zipfile.ZipFile(path) as archive:
names = {name.casefold(): name for name in archive.namelist()} names = {name.casefold(): name for name in archive.namelist()}
member = names.get(entry["zipped_file"].casefold()) member = names.get(entry["zipped_file"].casefold())
return bool(member) and hashlib.new(digest, archive.read(member)).hexdigest() in values return member is not None and hashlib.new(digest, archive.read(member)).hexdigest() in values
actual = hashlib.new(digest, path.read_bytes()).hexdigest() actual = hashlib.new(digest, path.read_bytes()).hexdigest()
if entry.get("zip_digest") != "composite" and actual in values: if entry.get("zip_digest") != "composite" and actual in values:
return True # whole digests, as batocera-systems:1088 compares them return True # whole digests, as batocera-systems:1088 compares them
if digest == DIGESTS["md5"] and path.suffix.lower() == ".zip": # Recalbox: members in name order if digest == DIGESTS["md5"] and path.suffix.lower() == ".zip": # Recalbox: members in name order
with zipfile.ZipFile(path) as archive: with zipfile.ZipFile(path) as archive:
names = sorted(name for name in archive.namelist() if not name.endswith("/")) members = sorted(name for name in archive.namelist() if not name.endswith("/"))
return hashlib.md5(b"".join(map(archive.read, names))).hexdigest() in values return hashlib.md5(b"".join(map(archive.read, members))).hexdigest() in values
except (OSError, zipfile.BadZipFile): except (OSError, zipfile.BadZipFile):
return False return False
return False return False
@@ -60,7 +60,7 @@ if __name__ == "__main__":
except urllib.request.HTTPError as error: # a 404: no platform has that name except urllib.request.HTTPError as error: # a 404: no platform has that name
with urllib.request.urlopen(API.replace("platforms/", "catalog.json")) as response: with urllib.request.urlopen(API.replace("platforms/", "catalog.json")) as response:
known = sorted(i["url"][10:-5] for i in json.load(response)["items"] if i["url"].startswith("manifests/")) known = sorted(i["url"][10:-5] for i in json.load(response)["items"] if i["url"].startswith("manifests/"))
sys.exit(f"unknown platform: {sys.argv[1]}. Known: {', '.join(known)}" if error.code == 404 else error) sys.exit(f"unknown platform: {sys.argv[1]}. Known: {', '.join(known)}" if error.code == 404 else str(error))
except OSError as error: # no such folder, or no network (URLError) except OSError as error: # no such folder, or no network (URLError)
sys.exit(f"error: {error}") sys.exit(f"error: {error}")
for verdict in ("ok", "wrong", "missing"): for verdict in ("ok", "wrong", "missing"):
+4 -3
View File
@@ -90,10 +90,11 @@ def compare(
served = next( served = next(
(name for name in _spellings(names[path]) if name in assets), None (name for name in _spellings(names[path]) if name in assets), None
) )
published = assets[served] if served else None if not served:
if published is None:
findings.append(AssetFinding("missing", path, size, None)) findings.append(AssetFinding("missing", path, size, None))
elif published != size: continue
published = assets[served]
if published != size:
findings.append(AssetFinding("size", path, size, published)) findings.append(AssetFinding("size", path, size, published))
else: else:
ours = (expected_digests or {}).get(path) ours = (expected_digests or {}).get(path)
+2 -3
View File
@@ -29,6 +29,7 @@ Usage:
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import contextlib
import os import os
import re import re
import shutil import shutil
@@ -81,10 +82,8 @@ def busy_paths() -> set[str]:
if not pid.name.isdigit(): if not pid.name.isdigit():
continue continue
links = [pid / "cwd"] links = [pid / "cwd"]
try: with contextlib.suppress(OSError):
links += list((pid / "fd").iterdir()) links += list((pid / "fd").iterdir())
except OSError:
pass
for link in links: for link in links:
try: try:
found.add(os.readlink(link)) found.add(os.readlink(link))
+3 -3
View File
@@ -186,10 +186,10 @@ class Checker:
self._files(where, entry["profile"], profile, entry.get("files") or []) self._files(where, entry["profile"], profile, entry.get("files") or [])
header = (entry.get("trigger") or {}).get("header") header = (entry.get("trigger") or {}).get("header")
if header and self.readers is not None: if header and self.readers is not None:
self._header(where, header) self._header(where, header, self.readers)
def _header(self, where: str, header: dict) -> None: def _header(self, where: str, header: dict, readers: dict[str, dict]) -> None:
reader = self.readers.get(header["reader"]) reader = readers.get(header["reader"])
if reader is None: if reader is None:
self.errors.append(f"{where}: games/headers.yml has no reader {header['reader']}") self.errors.append(f"{where}: games/headers.yml has no reader {header['reader']}")
return return
+3 -4
View File
@@ -156,9 +156,8 @@ def check_line(record: dict) -> list[str]:
problems.append(f"{rid}: id does not hash the first-layout record ({digest})") problems.append(f"{rid}: id does not hash the first-layout record ({digest})")
elif record_id(record) != rid: elif record_id(record) != rid:
problems.append(f"{rid}: id does not hash the record ({record_id(record)})") problems.append(f"{rid}: id does not hash the record ({record_id(record)})")
for key in ("emulator", "subject"): problems.extend(f"{rid}: {key} {record.get(key)!r} is not a lowercase slug"
if not SLUG_PATTERN.match(str(record.get(key, ""))): for key in ("emulator", "subject") if not SLUG_PATTERN.match(str(record.get(key, ""))))
problems.append(f"{rid}: {key} {record.get(key)!r} is not a lowercase slug")
return problems return problems
@@ -227,7 +226,7 @@ def read_records(root: Path) -> list[Stored]:
continue continue
if emulator in CAMPAIGN_FILES: if emulator in CAMPAIGN_FILES:
continue continue
seen: set[str] = set() seen: set[str | None] = set()
try: try:
records = parse_lines(files[path].read_text(encoding="utf-8"), path) records = parse_lines(files[path].read_text(encoding="utf-8"), path)
except RecordError as exc: except RecordError as exc:
+3 -3
View File
@@ -82,9 +82,9 @@ def shown(step: Step) -> str:
def execute(step: Step) -> int: def execute(step: Step) -> int:
env = {**os.environ, **step.env} env = {**os.environ, **step.env}
if not step.then: if not step.then:
return subprocess.run(argv(step.command), cwd=ROOT, env=env).returncode return subprocess.run(argv(step.command), cwd=ROOT, env=env, check=False).returncode
first = subprocess.run(argv(step.command), cwd=ROOT, env=env, stdout=subprocess.PIPE) first = subprocess.run(argv(step.command), cwd=ROOT, env=env, stdout=subprocess.PIPE, check=False)
return subprocess.run(argv(step.then), cwd=ROOT, env=env, input=first.stdout).returncode return subprocess.run(argv(step.then), cwd=ROOT, env=env, input=first.stdout, check=False).returncode
def run(steps: tuple[Step, ...] = STEPS) -> int: def run(steps: tuple[Step, ...] = STEPS) -> int:
+1 -2
View File
@@ -91,8 +91,7 @@ def plan_variants(entries: Iterable[dict], region: str,
local: Callable[[dict], Path | None]) -> dict[str, dict[str, Path]]: local: Callable[[dict], Path | None]) -> dict[str, dict[str, Path]]:
"""The staged files of `full`, `own` and `others`, dest -> file. An entry """The staged files of `full`, `own` and `others`, dest -> file. An entry
the collection does not hold is left out of every variant.""" the collection does not hold is left out of every variant."""
held = [(entry, local(entry)) for entry in entries] held = [(entry, path) for entry in entries if (path := local(entry))]
held = [(entry, path) for entry, path in held if path]
full = {entry_dest(e): p for e, p in held} full = {entry_dest(e): p for e, p in held}
own = {entry_dest(e): p for e, p in held if region in regions_of(e)} own = {entry_dest(e): p for e, p in held if region in regions_of(e)}
others = {entry_dest(e): p for e, p in held if region not in regions_of(e)} others = {entry_dest(e): p for e, p in held if region not in regions_of(e)}
+1 -1
View File
@@ -162,7 +162,7 @@ def _ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None:
return _INF return _INF
result = _INF result = _INF
addend = p addend: tuple[int, int] | None = p
while k: while k:
if k & 1: if k & 1:
result = _ec_add(result, addend) result = _ec_add(result, addend)