mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-29 12:58:51 -06:00
refactor: print the hash lookup from packs
This commit is contained in:
1 parent
3df143cbe1
commit
e36516f3b0
7 files changed
+177
-137
No files matched your search
+31
-105
@@ -9,9 +9,9 @@ from __future__ import annotations
|
||||
import contextlib
|
||||
import http.client
|
||||
import os
|
||||
import re
|
||||
import urllib.error
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from core import upstream
|
||||
@@ -176,130 +176,56 @@ def pending_release_asset(
|
||||
return None
|
||||
|
||||
|
||||
# Digest length in hex digits -> kind. A 29-digit MD5 is a value cut short,
|
||||
# looked up as the resolver looks one up (cut_md5_owner).
|
||||
_HASH_KINDS = {8: "crc32", 29: "md5", 32: "md5", 40: "sha1", 64: "sha256"}
|
||||
_HEX_DIGITS = re.compile(r"[0-9a-f]+")
|
||||
_WORD = re.compile(r"[0-9A-Za-z]+")
|
||||
ACCEPTED_HASHES = (
|
||||
"CRC32 (8 hex digits), MD5 (32, or the 29 Batocera writes), "
|
||||
"SHA-1 (40) or SHA-256 (64)"
|
||||
)
|
||||
|
||||
|
||||
def _detect_hash_type(h: str) -> str | None:
|
||||
"""The digest a hex string is, by its length, or None."""
|
||||
return _HASH_KINDS.get(len(h))
|
||||
|
||||
|
||||
def _hash_token(token: str) -> tuple[str, str] | None:
|
||||
"""(kind, value) when a token is a whole digest of a known length."""
|
||||
value = token.strip().lower().removeprefix("*").removeprefix("0x")
|
||||
kind = _detect_hash_type(value)
|
||||
if kind and _HEX_DIGITS.fullmatch(value):
|
||||
return kind, value
|
||||
return None
|
||||
|
||||
|
||||
def _refuse(rejected: list[str]) -> None:
|
||||
shown = ", ".join(rejected[:5]) + (", ..." if len(rejected) > 5 else "")
|
||||
raise ValueError(f"not a hash: {shown}. Accepted: {ACCEPTED_HASHES}")
|
||||
|
||||
|
||||
def parse_hash_input(raw: str) -> list[tuple[str, str]]:
|
||||
"""Parse a comma-separated hash string into (type, hash) tuples.
|
||||
|
||||
A part that is no digest is refused rather than dropped: a 12-digit
|
||||
value was looked up as an MD5 and reported NOT FOUND, and a SHA-256
|
||||
vanished without a word.
|
||||
"""
|
||||
results: list[tuple[str, str]] = []
|
||||
rejected: list[str] = []
|
||||
for part in raw.split(","):
|
||||
if not part.strip():
|
||||
continue
|
||||
parsed = _hash_token(part)
|
||||
if parsed:
|
||||
results.append(parsed)
|
||||
else:
|
||||
rejected.append(part.strip())
|
||||
if rejected:
|
||||
_refuse(rejected)
|
||||
return results
|
||||
|
||||
|
||||
def parse_hash_file(path: str) -> list[tuple[str, str]]:
|
||||
"""Parse a hash file: one hash per line, alone or beside a file name as
|
||||
md5sum writes it, ``#`` for comments. A line holding no digest is
|
||||
refused with its line number."""
|
||||
results: list[tuple[str, str]] = []
|
||||
rejected: list[str] = []
|
||||
with open(path) as f:
|
||||
for number, line in enumerate(f, 1):
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
parsed = next(
|
||||
(h for h in map(_hash_token, _WORD.findall(line)) if h), None
|
||||
)
|
||||
if parsed:
|
||||
results.append(parsed)
|
||||
else:
|
||||
rejected.append(f"line {number} ({line[:40]})")
|
||||
if rejected:
|
||||
_refuse(rejected)
|
||||
return results
|
||||
|
||||
|
||||
def sha1_for_hash(hash_type: str, hash_val: str, db: dict) -> str | None:
|
||||
"""The database key a looked-up hash names, or None."""
|
||||
return record_for_hash(db, hash_type, hash_val)
|
||||
|
||||
def lookup_hashes(
|
||||
hashes: list[tuple[str, str]],
|
||||
db: dict,
|
||||
bios_dir: str,
|
||||
emulators_dir: str,
|
||||
platforms_dir: str,
|
||||
) -> int:
|
||||
"""Print diagnostic info for each hash and return how many were not found."""
|
||||
missing = 0
|
||||
files_db = db.get("files", {})
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HashLookup:
|
||||
"""What the database and the disk say about one looked-up hash.
|
||||
|
||||
``sha1`` is empty when the database holds no file under the hash."""
|
||||
|
||||
kind: str
|
||||
value: str
|
||||
sha1: str = ""
|
||||
md5: str = ""
|
||||
name: str = ""
|
||||
path: str = ""
|
||||
in_repo: bool = False
|
||||
|
||||
@property
|
||||
def found(self) -> bool:
|
||||
return bool(self.sha1)
|
||||
|
||||
|
||||
def lookup_hashes(
|
||||
hashes: list[tuple[str, str]], db: dict, bios_dir: str,
|
||||
) -> list[HashLookup]:
|
||||
"""One record per hash: the file the database names, and whether the
|
||||
repository holds its bytes (at its path, or wherever resolution finds them)."""
|
||||
files_db = db.get("files", {})
|
||||
records: list[HashLookup] = []
|
||||
for hash_type, hash_val in hashes:
|
||||
sha1 = sha1_for_hash(hash_type, hash_val, db)
|
||||
if not sha1:
|
||||
print(f"\n{hash_type.upper()}: {hash_val}")
|
||||
print(" NOT FOUND in database")
|
||||
missing += 1
|
||||
records.append(HashLookup(hash_type, hash_val))
|
||||
continue
|
||||
|
||||
entry = files_db[sha1]
|
||||
name = entry.get("name", "?")
|
||||
md5 = entry.get("md5", "?")
|
||||
path = entry.get("path", "")
|
||||
|
||||
print(f"\n{hash_type.upper()}: {hash_val}")
|
||||
print(f" SHA1: {sha1}")
|
||||
print(f" MD5: {md5}")
|
||||
print(f" Name: {name}")
|
||||
if path:
|
||||
print(f" Path: {path}")
|
||||
|
||||
# Check if file exists in repo (by path or by resolve_local_file)
|
||||
in_repo = bool(path) and os.path.exists(path)
|
||||
if not in_repo:
|
||||
try:
|
||||
fe_check = {"name": name, "sha1": sha1, "md5": md5}
|
||||
local, status = resolve_file(fe_check, db, bios_dir, {})
|
||||
if local and status != "not_found":
|
||||
in_repo = True
|
||||
in_repo = bool(local) and status != "not_found"
|
||||
except (KeyError, OSError):
|
||||
pass
|
||||
print(f" In repo: {'YES' if in_repo else 'NO'}")
|
||||
if missing:
|
||||
print(f"\n{missing} of {len(hashes)} hash(es) not in the database")
|
||||
return missing
|
||||
records.append(HashLookup(hash_type, hash_val, sha1, md5, name, path, in_repo))
|
||||
return records
|
||||
|
||||
def resolve_file(
|
||||
file_entry: dict,
|
||||
|
||||
Reference in new issue
Block a user