mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
refactor: return auto_fetch searches as records
This commit is contained in:
1 parent
12c8d66163
commit
18472f9d0f
9 files changed
+450
-254
No files matched your search
+184
-186
@@ -7,15 +7,16 @@ import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.parse
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from acquire.placement import ACQUIRE_DIR, Placement, keep_acquired, place_file
|
||||
from core import upstream
|
||||
from core.hashing import parse_hash_list
|
||||
from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT
|
||||
from resolve.localfile import held_record_for
|
||||
from resolve.review import load_platform_hashes, load_profile_hashes, placement
|
||||
from resolve.review import load_platform_hashes, load_profile_hashes
|
||||
|
||||
MAX_DOWNLOAD = 100 * 1024 * 1024 # 100MB per file
|
||||
|
||||
@@ -183,41 +184,39 @@ def step2_scan_branches(entry: dict) -> bytes | None:
|
||||
return None
|
||||
|
||||
|
||||
# Sources that did not answer during the current file's search. A 404 is an
|
||||
# answer, the file is not there. Anything else leaves the question open: an
|
||||
# offline run used to report every file as needing a community contribution.
|
||||
_UNANSWERED: list[str] = []
|
||||
def _get(url: str, unanswered: list[str], timeout: float = 30) -> bytes | None:
|
||||
"""Body of a GET, None when there is none to check.
|
||||
|
||||
|
||||
def _get(url: str, timeout: float = 30) -> bytes | None:
|
||||
"""Body of a GET, None when there is none to check: a 404 and a body
|
||||
over MAX_DOWNLOAD are answers, any other failure is recorded in
|
||||
_UNANSWERED once the retries of core.upstream are spent."""
|
||||
A 404 and a body over MAX_DOWNLOAD are answers, the file is not there.
|
||||
Any other failure, once the retries of core.upstream are spent, leaves
|
||||
the question open and is added to *unanswered*: an offline run used to
|
||||
report every file as needing a community contribution.
|
||||
"""
|
||||
try:
|
||||
return upstream.fetch_body(
|
||||
url, timeout=timeout, max_bytes=MAX_DOWNLOAD, user_agent="retrobios-fetch/1.0"
|
||||
)
|
||||
except upstream.UpstreamError as exc:
|
||||
_UNANSWERED.append(f"{url}: {exc}")
|
||||
unanswered.append(f"{url}: {exc}")
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _get_json(url: str) -> dict:
|
||||
def _get_json(url: str, unanswered: list[str]) -> dict:
|
||||
"""A JSON object from a GET, {} when there is none."""
|
||||
body = _get(url)
|
||||
body = _get(url, unanswered)
|
||||
if body is None:
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except json.JSONDecodeError as exc:
|
||||
_UNANSWERED.append(f"{url}: {exc}")
|
||||
unanswered.append(f"{url}: {exc}")
|
||||
return {}
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
|
||||
|
||||
def step3_search_public_repos(entry: dict) -> bytes | None:
|
||||
def step3_search_public_repos(entry: dict, unanswered: list[str]) -> bytes | None:
|
||||
"""Search public GitHub BIOS repos."""
|
||||
name = entry["name"]
|
||||
destination = entry.get("destination", name)
|
||||
@@ -225,112 +224,177 @@ def step3_search_public_repos(entry: dict) -> bytes | None:
|
||||
names = [name, destination] if "/" in destination else [name]
|
||||
for url_template in PUBLIC_REPOS:
|
||||
for candidate in names:
|
||||
data = _get(url_template.format(name=candidate))
|
||||
data = _get(url_template.format(name=candidate), unanswered)
|
||||
if data is not None and verify_content(data, entry):
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
def step3b_software_heritage(entry: dict) -> bytes | None:
|
||||
def step3b_software_heritage(entry: dict, unanswered: list[str]) -> bytes | None:
|
||||
"""Ask Software Heritage for the file by each accepted sha1, then
|
||||
sha256: its archive answers by content, whatever the file was named."""
|
||||
for field in ("sha1", "sha256"):
|
||||
for value in sorted(parse_hash_list(entry.get(field))):
|
||||
data = _get(f"{SOFTWARE_HERITAGE}/{field}:{value}/raw/", timeout=60)
|
||||
for field_name in ("sha1", "sha256"):
|
||||
for value in sorted(parse_hash_list(entry.get(field_name))):
|
||||
data = _get(f"{SOFTWARE_HERITAGE}/{field_name}:{value}/raw/", unanswered,
|
||||
timeout=60)
|
||||
if data is not None and verify_content(data, entry):
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
def archive_org_by_sha1(sha1: str) -> bytes | None:
|
||||
def archive_org_by_sha1(sha1: str, unanswered: list[str]) -> bytes | None:
|
||||
"""The first archive.org file whose metadata names sha1, read and checked.
|
||||
|
||||
The member is chosen by its recorded sha1, never by its name: an item
|
||||
may store the dump under any path (bios/SCPH1001.BIN for scph1001.bin).
|
||||
"""
|
||||
search = ("https://archive.org/advancedsearch.php?q="
|
||||
f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5")
|
||||
docs = _get_json(search).get("response", {}).get("docs", [])
|
||||
search_url = ("https://archive.org/advancedsearch.php?q="
|
||||
f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5")
|
||||
docs = _get_json(search_url, unanswered).get("response", {}).get("docs", [])
|
||||
for doc in docs:
|
||||
identifier = doc.get("identifier")
|
||||
if not identifier:
|
||||
continue
|
||||
files = _get_json(f"https://archive.org/metadata/{identifier}/files").get("result", [])
|
||||
files = _get_json(
|
||||
f"https://archive.org/metadata/{identifier}/files", unanswered
|
||||
).get("result", [])
|
||||
for item in files:
|
||||
if str(item.get("sha1", "")).lower() != sha1:
|
||||
continue
|
||||
url = (f"https://archive.org/download/{identifier}/"
|
||||
f"{urllib.parse.quote(item['name'])}")
|
||||
data = _get(url, timeout=60)
|
||||
data = _get(url, unanswered, timeout=60)
|
||||
if data is not None and hashlib.sha1(data).hexdigest() == sha1:
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
def step4_search_archive_org(entry: dict) -> bytes | None:
|
||||
def step4_search_archive_org(entry: dict, unanswered: list[str]) -> bytes | None:
|
||||
"""Search archive.org firmware collections by direct download, then
|
||||
every item by each accepted sha1."""
|
||||
name = entry["name"]
|
||||
|
||||
for collection_id in ARCHIVE_ORG_COLLECTIONS:
|
||||
for path in [name, f"system/{name}", f"bios/{name}"]:
|
||||
data = _get(f"https://archive.org/download/{collection_id}/{path}")
|
||||
data = _get(f"https://archive.org/download/{collection_id}/{path}", unanswered)
|
||||
if data is not None and verify_content(data, entry):
|
||||
return data
|
||||
|
||||
for sha1 in sorted(parse_hash_list(entry.get("sha1"))):
|
||||
data = archive_org_by_sha1(sha1)
|
||||
data = archive_org_by_sha1(sha1, unanswered)
|
||||
if data is not None and verify_content(data, entry):
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
def place_file(
|
||||
data: bytes, entry: dict, bios_dir: str, db: dict,
|
||||
platform_hashes: dict, profile_hashes: dict,
|
||||
) -> str:
|
||||
"""Write a fetched file where the review would accept it.
|
||||
@dataclass(frozen=True)
|
||||
class SearchResult:
|
||||
"""What one file's search found, where, and which sources did not answer."""
|
||||
|
||||
The folder is resolve.review.placement()'s, the rule validate_pr and the
|
||||
wanted page read: a slug matched against folder names sent nintendo-ds
|
||||
to Nintendo/3DS and snk-neogeo to a new Unknown/ folder. A system whose
|
||||
folder is not settled leaves the file in tmp/acquire/, never in bios/.
|
||||
data: bytes | None
|
||||
source: str | None
|
||||
unanswered: tuple[str, ...]
|
||||
|
||||
|
||||
# The sources a platform's missing file is searched in, in order.
|
||||
PLATFORM_SOURCES = ("branch", "public_repo", "software_heritage", "archive_org")
|
||||
# The sources a bare sha1 is searched in, in order.
|
||||
SHA1_SOURCES = ("software_heritage", "archive_org_sha1")
|
||||
|
||||
|
||||
def _ask(source: str, entry: dict, unanswered: list[str]) -> bytes | None:
|
||||
"""The verified bytes one source holds for an entry, None when it holds none."""
|
||||
if source == "branch":
|
||||
return step2_scan_branches(entry)
|
||||
if source == "public_repo":
|
||||
return step3_search_public_repos(entry, unanswered)
|
||||
if source == "software_heritage":
|
||||
return step3b_software_heritage(entry, unanswered)
|
||||
if source == "archive_org":
|
||||
return step4_search_archive_org(entry, unanswered)
|
||||
if source == "archive_org_sha1":
|
||||
return archive_org_by_sha1(entry["sha1"], unanswered)
|
||||
raise ValueError(f"unknown source {source}")
|
||||
|
||||
|
||||
def search(entry: dict, sources: tuple[str, ...]) -> SearchResult:
|
||||
"""Ask each source in turn and stop at the first that serves the file."""
|
||||
unanswered: list[str] = []
|
||||
for source in sources:
|
||||
data = _ask(source, entry, unanswered)
|
||||
if data:
|
||||
return SearchResult(data, source, tuple(unanswered))
|
||||
return SearchResult(None, None, tuple(unanswered))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FetchRecord:
|
||||
"""The outcome of one missing file's search.
|
||||
|
||||
outcome is held, unverifiable, dry_run, found, incomplete or not_found.
|
||||
"""
|
||||
name = os.path.basename(entry["name"])
|
||||
system = str(entry.get("system") or "")
|
||||
root = Path(bios_dir)
|
||||
|
||||
def local(path: str) -> Path:
|
||||
# placement() speaks repository paths, bios/<Manufacturer>/...
|
||||
return root.joinpath(*path.rstrip("/").split("/")[1:])
|
||||
entry: dict
|
||||
outcome: str
|
||||
held_at: str | None = None
|
||||
source: str | None = None
|
||||
placed: Placement | None = None
|
||||
unanswered: tuple[str, ...] = ()
|
||||
|
||||
values = [
|
||||
*parse_hash_list(entry.get("sha1")),
|
||||
*parse_hash_list(entry.get("md5")),
|
||||
*parse_hash_list(entry.get("sha256")),
|
||||
]
|
||||
spot = placement(
|
||||
values, name, db, platform_hashes, profile_hashes, declared=bool(values),
|
||||
systems=[system] if system else [], exists=lambda path: local(path).exists(),
|
||||
)
|
||||
folders: tuple[str, ...] = spot.folders or ((spot.home,) if spot.home else ())
|
||||
sha1 = hashlib.sha1(data).hexdigest()
|
||||
if len(folders) != 1:
|
||||
print(f" No single bios/ folder for {system or name}"
|
||||
+ (f" ({', '.join(folders)})" if folders else "")
|
||||
+ ": kept out of bios/")
|
||||
dest = ACQUIRE_DIR / sha1
|
||||
else:
|
||||
folder = local(folders[0])
|
||||
dest = folder / (spot.name or name)
|
||||
if dest.exists() and dest.read_bytes() != data:
|
||||
# Another revision under the same name: the collection keeps it
|
||||
# beside, never in place of, the file already there.
|
||||
dest = folder / ".variants" / f"{dest.name}.{sha1[:8]}"
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(dest, "wb") as f:
|
||||
f.write(data)
|
||||
return str(dest)
|
||||
|
||||
@dataclass
|
||||
class FetchRun:
|
||||
"""Searches the missing files of one platform and places what it finds."""
|
||||
|
||||
db: dict
|
||||
bios_dir: str
|
||||
dry_run: bool = False
|
||||
platforms_dir: str = PLATFORMS_DIR
|
||||
emulators_dir: str = EMULATORS_DIR
|
||||
acquire_dir: Path = ACQUIRE_DIR
|
||||
_tables: list[dict] = field(default_factory=list)
|
||||
|
||||
def _place(self, data: bytes, entry: dict) -> Placement:
|
||||
# Read once, and only when something was found to place.
|
||||
if not self._tables:
|
||||
self._tables.extend((load_platform_hashes(self.platforms_dir, self.db),
|
||||
load_profile_hashes(self.emulators_dir, self.db)))
|
||||
return place_file(data, entry, self.bios_dir, self.db, *self._tables,
|
||||
acquire_dir=self.acquire_dir)
|
||||
|
||||
def fetch(self, entry: dict) -> FetchRecord:
|
||||
"""Look for one file, from the database out to archive.org."""
|
||||
existing = step1_crossref_db(entry, self.db)
|
||||
if existing:
|
||||
return FetchRecord(entry, "held", held_at=existing)
|
||||
if not verifiable(entry):
|
||||
# A file of that name could only ever be refused.
|
||||
return FetchRecord(entry, "unverifiable")
|
||||
if self.dry_run:
|
||||
return FetchRecord(entry, "dry_run")
|
||||
found = search(entry, PLATFORM_SOURCES)
|
||||
if found.data:
|
||||
return FetchRecord(entry, "found", source=found.source,
|
||||
placed=self._place(found.data, entry),
|
||||
unanswered=found.unanswered)
|
||||
# Not looked for everywhere: no issue asks the community for it.
|
||||
outcome = "incomplete" if found.unanswered else "not_found"
|
||||
return FetchRecord(entry, outcome, unanswered=found.unanswered)
|
||||
|
||||
|
||||
# The count each outcome adds to, and the outcomes still open for contributions.
|
||||
_COUNTED = {"held": "found", "found": "found", "unverifiable": "unverifiable",
|
||||
"dry_run": "not_found", "not_found": "not_found", "incomplete": "errors"}
|
||||
_STILL_MISSING = ("unverifiable", "dry_run", "not_found")
|
||||
|
||||
|
||||
def fetch_summary(records: list[FetchRecord]) -> dict:
|
||||
"""The counts a run reports and the files still open for contributions."""
|
||||
stats = {"found": 0, "not_found": 0, "errors": 0, "unverifiable": 0}
|
||||
for record in records:
|
||||
stats[_COUNTED[record.outcome]] += 1
|
||||
still_missing = [r.entry for r in records if r.outcome in _STILL_MISSING]
|
||||
return {"stats": stats, "still_missing": still_missing}
|
||||
|
||||
|
||||
def fetch_missing(
|
||||
@@ -340,125 +404,59 @@ def fetch_missing(
|
||||
dry_run: bool = False,
|
||||
platforms_dir: str = PLATFORMS_DIR,
|
||||
emulators_dir: str = EMULATORS_DIR,
|
||||
acquire_dir: Path = ACQUIRE_DIR,
|
||||
) -> dict:
|
||||
"""Run the 5-step auto-fetch pipeline for missing files."""
|
||||
stats = {"found": 0, "not_found": 0, "errors": 0, "unverifiable": 0}
|
||||
still_missing = []
|
||||
tables: list[dict] = []
|
||||
|
||||
def place(data: bytes, entry: dict) -> str:
|
||||
# Read once, and only when something was found to place.
|
||||
if not tables:
|
||||
tables.extend((load_platform_hashes(platforms_dir, db),
|
||||
load_profile_hashes(emulators_dir, db)))
|
||||
return place_file(data, entry, bios_dir, db, *tables)
|
||||
|
||||
for entry in missing:
|
||||
name = entry["name"]
|
||||
_UNANSWERED.clear()
|
||||
print(f"\n Searching: {name} ({entry['system']})")
|
||||
|
||||
existing = step1_crossref_db(entry, db)
|
||||
if existing:
|
||||
print(f" [1] Found in database at: {existing}")
|
||||
stats["found"] += 1
|
||||
continue
|
||||
|
||||
if not verifiable(entry):
|
||||
# Searched, a file of that name could only ever be refused.
|
||||
print(" [-] Cannot be verified from the network: declares no "
|
||||
"cryptographic hash. Not searched, nothing written")
|
||||
still_missing.append(entry)
|
||||
stats["unverifiable"] += 1
|
||||
continue
|
||||
|
||||
if dry_run:
|
||||
print(" [DRY RUN] Would search branches, repos, Software Heritage, archive.org")
|
||||
still_missing.append(entry)
|
||||
stats["not_found"] += 1
|
||||
continue
|
||||
|
||||
data = step2_scan_branches(entry)
|
||||
if data:
|
||||
path = place(data, entry)
|
||||
print(f" [2] Found in branch, saved to: {path}")
|
||||
stats["found"] += 1
|
||||
continue
|
||||
|
||||
data = step3_search_public_repos(entry)
|
||||
if data:
|
||||
path = place(data, entry)
|
||||
print(f" [3] Found in public repo, saved to: {path}")
|
||||
stats["found"] += 1
|
||||
continue
|
||||
|
||||
data = step3b_software_heritage(entry)
|
||||
if data:
|
||||
path = place(data, entry)
|
||||
print(f" [3b] Found in Software Heritage, saved to: {path}")
|
||||
stats["found"] += 1
|
||||
continue
|
||||
|
||||
data = step4_search_archive_org(entry)
|
||||
if data:
|
||||
path = place(data, entry)
|
||||
print(f" [4] Found on archive.org, saved to: {path}")
|
||||
stats["found"] += 1
|
||||
continue
|
||||
|
||||
if _UNANSWERED:
|
||||
# Not looked for everywhere: no issue asks the community for it.
|
||||
print(
|
||||
f" [5] Search incomplete, {len(_UNANSWERED)} source(s) did not "
|
||||
f"answer (first: {_UNANSWERED[0]})"
|
||||
)
|
||||
stats["errors"] += 1
|
||||
continue
|
||||
print(" [5] Not found, open for contributions")
|
||||
still_missing.append(entry)
|
||||
stats["not_found"] += 1
|
||||
|
||||
return {"stats": stats, "still_missing": still_missing}
|
||||
"""Search every missing file: the counts, the files still open and the records."""
|
||||
run = FetchRun(db, bios_dir, dry_run, platforms_dir, emulators_dir, acquire_dir)
|
||||
records = [run.fetch(entry) for entry in missing]
|
||||
return {**fetch_summary(records), "records": records}
|
||||
|
||||
|
||||
ACQUIRE_DIR = Path("tmp") / "acquire"
|
||||
@dataclass(frozen=True)
|
||||
class LookupRecord:
|
||||
"""The outcome of one --sha1 lookup.
|
||||
|
||||
outcome is malformed, held, dry_run, not_found or found.
|
||||
"""
|
||||
|
||||
raw: str
|
||||
sha1: str
|
||||
outcome: str
|
||||
held_at: str | None = None
|
||||
source: str | None = None
|
||||
size: int = 0
|
||||
path: Path | None = None
|
||||
unanswered: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int:
|
||||
"""--sha1: each file looked for by its hash alone, without a platform.
|
||||
Found bytes are verified, then saved as tmp/acquire/<sha1>, never into
|
||||
bios/: placing a file is a decision the collection makes. 0 when every
|
||||
one was found, 1 otherwise."""
|
||||
missing = 0
|
||||
for raw in sha1s:
|
||||
sha1 = raw.strip().lower()
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", sha1):
|
||||
print(f" {raw}: not a sha1", file=sys.stderr)
|
||||
missing += 1
|
||||
continue
|
||||
entry = {"name": sha1, "sha1": sha1, "system": ""}
|
||||
_UNANSWERED.clear()
|
||||
held = step1_crossref_db(entry, db)
|
||||
if held:
|
||||
print(f" {sha1}: already held at {held}")
|
||||
continue
|
||||
if dry_run:
|
||||
print(f" {sha1}: would ask Software Heritage and archive.org")
|
||||
continue
|
||||
data = step3b_software_heritage(entry)
|
||||
where = "Software Heritage"
|
||||
if data is None:
|
||||
data, where = archive_org_by_sha1(sha1), "archive.org"
|
||||
if data is None:
|
||||
note = f", {len(_UNANSWERED)} source(s) did not answer" if _UNANSWERED else ""
|
||||
print(f" {sha1}: not found{note}")
|
||||
missing += 1
|
||||
continue
|
||||
ACQUIRE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
out = ACQUIRE_DIR / sha1
|
||||
out.write_bytes(data)
|
||||
print(f" {sha1}: found in {where}, {len(data)} bytes, saved to {out}")
|
||||
return 1 if missing else 0
|
||||
def lookup_sha1(raw: str, db: dict, dry_run: bool = False,
|
||||
acquire_dir: Path = ACQUIRE_DIR) -> LookupRecord:
|
||||
"""--sha1: one file looked for by its hash alone, without a platform.
|
||||
|
||||
Found bytes are verified, then saved as <acquire_dir>/<sha1>, never into
|
||||
bios/: placing a file is a decision the collection makes.
|
||||
"""
|
||||
sha1 = raw.strip().lower()
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", sha1):
|
||||
return LookupRecord(raw, sha1, "malformed")
|
||||
entry = {"name": sha1, "sha1": sha1, "system": ""}
|
||||
held = step1_crossref_db(entry, db)
|
||||
if held:
|
||||
return LookupRecord(raw, sha1, "held", held_at=held)
|
||||
if dry_run:
|
||||
return LookupRecord(raw, sha1, "dry_run")
|
||||
found = search(entry, SHA1_SOURCES)
|
||||
if found.data is None:
|
||||
return LookupRecord(raw, sha1, "not_found", unanswered=found.unanswered)
|
||||
out = keep_acquired(found.data, sha1, acquire_dir)
|
||||
return LookupRecord(raw, sha1, "found", source=found.source, size=len(found.data),
|
||||
path=out, unanswered=found.unanswered)
|
||||
|
||||
|
||||
def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False,
|
||||
acquire_dir: Path = ACQUIRE_DIR) -> list[LookupRecord]:
|
||||
"""Each --sha1 looked up in turn."""
|
||||
return [lookup_sha1(raw, db, dry_run, acquire_dir) for raw in sha1s]
|
||||
|
||||
|
||||
CONTRIBUTING_URL = "https://github.com/Abdess/retrobios/blob/main/CONTRIBUTING.md"
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""The lines auto_fetch prints for each search, and its exit code for --sha1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from acquire.fetch import FetchRecord, FetchRun, LookupRecord, fetch_summary, lookup_sha1
|
||||
from acquire.placement import ACQUIRE_DIR
|
||||
from core.paths import EMULATORS_DIR, PLATFORMS_DIR
|
||||
|
||||
# The step number and wording of each source that served a platform's file.
|
||||
FOUND_IN = {
|
||||
"branch": "[2] Found in branch",
|
||||
"public_repo": "[3] Found in public repo",
|
||||
"software_heritage": "[3b] Found in Software Heritage",
|
||||
"archive_org": "[4] Found on archive.org",
|
||||
}
|
||||
# The name of each source that served a --sha1 lookup.
|
||||
SHA1_FOUND_IN = {"software_heritage": "Software Heritage", "archive_org_sha1": "archive.org"}
|
||||
|
||||
|
||||
def fetch_lines(record: FetchRecord) -> list[str]:
|
||||
"""What a platform run prints once one file's search is over."""
|
||||
if record.outcome == "held":
|
||||
return [f" [1] Found in database at: {record.held_at}"]
|
||||
if record.outcome == "unverifiable":
|
||||
return [" [-] Cannot be verified from the network: declares no "
|
||||
"cryptographic hash. Not searched, nothing written"]
|
||||
if record.outcome == "dry_run":
|
||||
return [" [DRY RUN] Would search branches, repos, Software Heritage, archive.org"]
|
||||
if record.outcome == "incomplete":
|
||||
return [f" [5] Search incomplete, {len(record.unanswered)} source(s) did not "
|
||||
f"answer (first: {record.unanswered[0]})"]
|
||||
if record.outcome == "not_found":
|
||||
return [" [5] Not found, open for contributions"]
|
||||
lines = []
|
||||
placed = record.placed
|
||||
assert placed is not None and record.source is not None
|
||||
if placed.kept_out:
|
||||
label = str(record.entry.get("system") or "") or os.path.basename(record.entry["name"])
|
||||
lines.append(f" No single bios/ folder for {label}"
|
||||
+ (f" ({', '.join(placed.folders)})" if placed.folders else "")
|
||||
+ ": kept out of bios/")
|
||||
lines.append(f" {FOUND_IN[record.source]}, saved to: {placed.path}")
|
||||
return lines
|
||||
|
||||
|
||||
def report_fetch(
|
||||
missing: list[dict],
|
||||
db: dict,
|
||||
bios_dir: str,
|
||||
dry_run: bool = False,
|
||||
platforms_dir: str = PLATFORMS_DIR,
|
||||
emulators_dir: str = EMULATORS_DIR,
|
||||
acquire_dir: Path = ACQUIRE_DIR,
|
||||
) -> dict:
|
||||
"""Search every missing file, printing each search as it runs."""
|
||||
run = FetchRun(db, bios_dir, dry_run, platforms_dir, emulators_dir, acquire_dir)
|
||||
records = []
|
||||
for entry in missing:
|
||||
print(f"\n Searching: {entry['name']} ({entry['system']})")
|
||||
record = run.fetch(entry)
|
||||
for line in fetch_lines(record):
|
||||
print(line)
|
||||
records.append(record)
|
||||
return {**fetch_summary(records), "records": records}
|
||||
|
||||
|
||||
def lookup_line(record: LookupRecord) -> str:
|
||||
"""What --sha1 prints for one lookup."""
|
||||
if record.outcome == "malformed":
|
||||
return f" {record.raw}: not a sha1"
|
||||
if record.outcome == "held":
|
||||
return f" {record.sha1}: already held at {record.held_at}"
|
||||
if record.outcome == "dry_run":
|
||||
return f" {record.sha1}: would ask Software Heritage and archive.org"
|
||||
if record.outcome == "not_found":
|
||||
note = (f", {len(record.unanswered)} source(s) did not answer"
|
||||
if record.unanswered else "")
|
||||
return f" {record.sha1}: not found{note}"
|
||||
assert record.source is not None
|
||||
return (f" {record.sha1}: found in {SHA1_FOUND_IN[record.source]}, "
|
||||
f"{record.size} bytes, saved to {record.path}")
|
||||
|
||||
|
||||
def report_lookups(sha1s: list[str], db: dict, dry_run: bool = False,
|
||||
acquire_dir: Path = ACQUIRE_DIR) -> int:
|
||||
"""Look up each --sha1, printing each answer: 0 when every one was found, 1 otherwise."""
|
||||
missing = 0
|
||||
for raw in sha1s:
|
||||
record = lookup_sha1(raw, db, dry_run, acquire_dir)
|
||||
malformed = record.outcome == "malformed"
|
||||
print(lookup_line(record), file=sys.stderr if malformed else sys.stdout)
|
||||
missing += malformed or record.outcome == "not_found"
|
||||
return 1 if missing else 0
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Where a fetched file is written: its bios/ folder, or the acquire folder when none is settled."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from core.hashing import parse_hash_list
|
||||
from core.paths import REPO_ROOT
|
||||
from resolve.review import placement
|
||||
|
||||
# Found files the collection has not placed yet, by sha1. Under the
|
||||
# repository whatever the working directory: a run from another folder wrote
|
||||
# them somewhere nobody looked.
|
||||
ACQUIRE_DIR = REPO_ROOT / "tmp" / "acquire"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Placement:
|
||||
"""Where a fetched file was written, and the folders that left it out of bios/."""
|
||||
|
||||
path: str
|
||||
kept_out: bool = False
|
||||
folders: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def place_file(
|
||||
data: bytes, entry: dict, bios_dir: str, db: dict,
|
||||
platform_hashes: dict, profile_hashes: dict, acquire_dir: Path = ACQUIRE_DIR,
|
||||
) -> Placement:
|
||||
"""Write a fetched file where the review would accept it.
|
||||
|
||||
The folder is resolve.review.placement()'s, the rule validate_pr and the
|
||||
wanted page read: a slug matched against folder names sent nintendo-ds
|
||||
to Nintendo/3DS and snk-neogeo to a new Unknown/ folder. A system whose
|
||||
folder is not settled leaves the file in acquire_dir, never in bios/.
|
||||
"""
|
||||
name = os.path.basename(entry["name"])
|
||||
system = str(entry.get("system") or "")
|
||||
root = Path(bios_dir)
|
||||
|
||||
def local(path: str) -> Path:
|
||||
# placement() speaks repository paths, bios/<Manufacturer>/...
|
||||
return root.joinpath(*path.rstrip("/").split("/")[1:])
|
||||
|
||||
values = [
|
||||
*parse_hash_list(entry.get("sha1")),
|
||||
*parse_hash_list(entry.get("md5")),
|
||||
*parse_hash_list(entry.get("sha256")),
|
||||
]
|
||||
spot = placement(
|
||||
values, name, db, platform_hashes, profile_hashes, declared=bool(values),
|
||||
systems=[system] if system else [], exists=lambda path: local(path).exists(),
|
||||
)
|
||||
folders: tuple[str, ...] = spot.folders or ((spot.home,) if spot.home else ())
|
||||
sha1 = hashlib.sha1(data).hexdigest()
|
||||
kept_out = len(folders) != 1
|
||||
if kept_out:
|
||||
dest = acquire_dir / sha1
|
||||
else:
|
||||
folder = local(folders[0])
|
||||
dest = folder / (spot.name or name)
|
||||
if dest.exists() and dest.read_bytes() != data:
|
||||
# Another revision under the same name: the collection keeps it
|
||||
# beside, never in place of, the file already there.
|
||||
dest = folder / ".variants" / f"{dest.name}.{sha1[:8]}"
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(dest, "wb") as f:
|
||||
f.write(data)
|
||||
return Placement(str(dest), kept_out, folders)
|
||||
|
||||
|
||||
def keep_acquired(data: bytes, sha1: str, acquire_dir: Path | None = None) -> Path:
|
||||
"""Write found bytes as <acquire_dir>/<sha1>, out of bios/: placing them is the collection's decision."""
|
||||
folder = acquire_dir or ACQUIRE_DIR
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
out = folder / sha1
|
||||
out.write_bytes(data)
|
||||
return out
|
||||
@@ -26,7 +26,8 @@ from core.cli import add_repo_inputs, require_directory
|
||||
from model.database import load_database, load_optional_database
|
||||
from model.platforms import load_platform_config
|
||||
from model.safeparse import require_yaml
|
||||
from acquire.fetch import fetch_missing, find_missing, generate_issue_body, lookup_sha1s
|
||||
from acquire.fetch import find_missing, generate_issue_body
|
||||
from acquire.fetchtext import report_fetch, report_lookups
|
||||
|
||||
yaml = require_yaml()
|
||||
|
||||
@@ -54,7 +55,7 @@ def main() -> None:
|
||||
parser.error("--sha1 looks for files by hash alone: it takes no "
|
||||
"--platform, --all or --create-issues")
|
||||
db = load_optional_database(args.db) or {"files": {}}
|
||||
sys.exit(lookup_sha1s(args.sha1, db, args.dry_run))
|
||||
sys.exit(report_lookups(args.sha1, db, args.dry_run))
|
||||
|
||||
db = load_database(args.db)
|
||||
|
||||
@@ -79,7 +80,7 @@ def main() -> None:
|
||||
continue
|
||||
|
||||
print(f" {len(missing)} missing files")
|
||||
result = fetch_missing(missing, db, args.bios_dir, args.dry_run, args.platforms_dir)
|
||||
result = report_fetch(missing, db, args.bios_dir, args.dry_run, args.platforms_dir)
|
||||
|
||||
if result["still_missing"]:
|
||||
all_still_missing[config.get("platform") or platform] = result["still_missing"]
|
||||
|
||||
@@ -24,7 +24,7 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
from acquire.embedded import offsets, sources
|
||||
from acquire.fetch import ACQUIRE_DIR
|
||||
from acquire.placement import keep_acquired
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -58,10 +58,7 @@ def main() -> int:
|
||||
print(f" {label} at {offset}: sha1 {sha1}"
|
||||
+ (" (confirmed)" if wanted_sha1 else " (crc32 only, give --sha1)"))
|
||||
if args.extract:
|
||||
ACQUIRE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
out = ACQUIRE_DIR / sha1
|
||||
out.write_bytes(window)
|
||||
print(f" written to {out}")
|
||||
print(f" written to {keep_acquired(window, sha1)}")
|
||||
if not confirmed and not candidates:
|
||||
print("Not found.")
|
||||
return 0 if confirmed or (candidates and not wanted_sha1) else 1
|
||||
|
||||
+2
-2
@@ -100,8 +100,8 @@ COMMANDS = {
|
||||
"romrecipes/text.py", "romrecipes/runs.py",
|
||||
),
|
||||
"provenance_report.py": ("acquire/provenance.py",),
|
||||
"auto_fetch.py": ("acquire/fetch.py",),
|
||||
"find_embedded.py": ("acquire/embedded.py",),
|
||||
"auto_fetch.py": ("acquire/fetch.py", "acquire/fetchtext.py", "acquire/placement.py"),
|
||||
"find_embedded.py": ("acquire/embedded.py", "acquire/placement.py"),
|
||||
"find_pinned_revision.py": ("acquire/history.py",),
|
||||
"check_freshness.py": (
|
||||
"freshness/findings.py", "freshness/platformdiff.py", "freshness/rescrape.py",
|
||||
|
||||
@@ -948,7 +948,7 @@ class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase):
|
||||
return {"system_folders": {system: {folder}}}, {}
|
||||
|
||||
def test_the_review_folder_is_used_and_nothing_is_overwritten(self):
|
||||
from scripts.acquire import fetch as acquire_fetch
|
||||
from scripts.acquire import placement as acquire_placement
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
bios = Path(directory)
|
||||
@@ -956,45 +956,43 @@ class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase):
|
||||
(bios / folder).mkdir(parents=True)
|
||||
held = bios / "Nintendo" / "N64" / "n64.psh"
|
||||
held.write_bytes(b"other revision")
|
||||
placed = Path(acquire_fetch.place_file(
|
||||
placed = Path(acquire_placement.place_file(
|
||||
b"fetched", {"name": "n64.psh", "system": "nintendo-64"}, str(bios), {},
|
||||
*self._tables("nintendo-64", "bios/Nintendo/N64/"),
|
||||
))
|
||||
).path)
|
||||
self.assertEqual(placed.parent.parent, bios / "Nintendo" / "N64")
|
||||
self.assertEqual(placed.parent.name, ".variants")
|
||||
self.assertEqual(held.read_bytes(), b"other revision")
|
||||
|
||||
def test_a_slug_inside_another_folder_name_is_no_folder(self):
|
||||
"""'ds' is in '3DS': the DS firmware went to Nintendo/3DS."""
|
||||
from scripts.acquire import fetch as acquire_fetch
|
||||
from scripts.acquire import placement as acquire_placement
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
bios = Path(directory)
|
||||
for folder in ("Nintendo/3DS", "Nintendo/Nintendo DS"):
|
||||
(bios / folder).mkdir(parents=True)
|
||||
placed = Path(acquire_fetch.place_file(
|
||||
placed = Path(acquire_placement.place_file(
|
||||
b"fw", {"name": "firmware.bin", "system": "nintendo-ds"}, str(bios), {},
|
||||
*self._tables("nintendo-ds", "bios/Nintendo/Nintendo DS/"),
|
||||
))
|
||||
).path)
|
||||
self.assertEqual(placed, bios / "Nintendo" / "Nintendo DS" / "firmware.bin")
|
||||
|
||||
def test_an_unsettled_folder_stays_out_of_bios(self):
|
||||
"""snk-neogeo went to a new bios/Unknown/snk-neogeo/."""
|
||||
import hashlib
|
||||
from unittest import mock
|
||||
|
||||
from scripts.acquire import fetch as acquire_fetch
|
||||
from scripts.acquire import placement as acquire_placement
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
bios, acquired = Path(directory, "bios"), Path(directory, "acquire")
|
||||
bios.mkdir()
|
||||
with mock.patch.object(acquire_fetch, "ACQUIRE_DIR", acquired), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
placed = Path(acquire_fetch.place_file(
|
||||
b"set", {"name": "neogeo.zip", "system": "snk-neogeo"}, str(bios), {},
|
||||
{}, {},
|
||||
))
|
||||
self.assertEqual(placed, acquired / hashlib.sha1(b"set").hexdigest())
|
||||
placed = acquire_placement.place_file(
|
||||
b"set", {"name": "neogeo.zip", "system": "snk-neogeo"}, str(bios), {},
|
||||
{}, {}, acquire_dir=acquired,
|
||||
)
|
||||
self.assertTrue(placed.kept_out)
|
||||
self.assertEqual(Path(placed.path), acquired / hashlib.sha1(b"set").hexdigest())
|
||||
self.assertEqual(list(bios.iterdir()), [])
|
||||
|
||||
|
||||
@@ -6906,8 +6904,7 @@ class AnUnansweredSearchIsNotANotFound(unittest.TestCase):
|
||||
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}}}
|
||||
with mock.patch("urllib.request.urlopen", refuse), \
|
||||
mock.patch.object(acquire_fetch.upstream, "_sleep", lambda _s: None), \
|
||||
mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None):
|
||||
return acquire_fetch.fetch_missing([entry], db, "bios")
|
||||
|
||||
def test_offline_is_not_searched(self):
|
||||
@@ -6969,13 +6966,12 @@ class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as bios, \
|
||||
mock.patch.object(urllib.request, "urlopen", lambda *a, **k: served), \
|
||||
mock.patch.object(acquire_fetch, "step2_scan_branches",
|
||||
lambda e: self.DATA), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
lambda e: self.DATA):
|
||||
result = acquire_fetch.fetch_missing([crc], {"files": {}}, bios)
|
||||
self.assertEqual(list(Path(bios).rglob("*")), [])
|
||||
self.assertEqual(result["stats"]["found"], 0)
|
||||
self.assertEqual(result["stats"]["unverifiable"], 1)
|
||||
self.assertIn("declares no cryptographic hash", out.getvalue())
|
||||
self.assertEqual([r.outcome for r in result["records"]], ["unverifiable"])
|
||||
|
||||
def test_a_held_sha256_is_found_in_the_database(self):
|
||||
from scripts.acquire import fetch as acquire_fetch
|
||||
@@ -7005,13 +7001,14 @@ class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase):
|
||||
def test_an_entry_without_a_hash_is_not_searched(self):
|
||||
from unittest import mock
|
||||
|
||||
from scripts.acquire import fetch as acquire_fetch
|
||||
from acquire import fetch as acquire_fetch
|
||||
from acquire import fetchtext
|
||||
|
||||
entry = {"name": "DICROM.ROM", "system": "fujitsu-fm7"}
|
||||
out = io.StringIO()
|
||||
with mock.patch.object(acquire_fetch, "step2_scan_branches") as branches, \
|
||||
contextlib.redirect_stdout(out):
|
||||
result = acquire_fetch.fetch_missing([entry], {"files": {}}, "bios", dry_run=True)
|
||||
result = fetchtext.report_fetch([entry], {"files": {}}, "bios", dry_run=True)
|
||||
branches.assert_not_called()
|
||||
self.assertEqual(result["stats"]["unverifiable"], 1)
|
||||
self.assertNotIn("Would search", out.getvalue())
|
||||
|
||||
@@ -15,7 +15,7 @@ import urllib.error
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from acquire import fetch
|
||||
from acquire import fetch, fetchtext
|
||||
|
||||
PAYLOAD = b"keyboard mcu"
|
||||
SHA1 = hashlib.sha1(PAYLOAD).hexdigest()
|
||||
@@ -48,47 +48,51 @@ class SoftwareHeritageAnswersByContent(unittest.TestCase):
|
||||
def test_the_bytes_it_serves_are_kept_when_the_hash_holds(self):
|
||||
urlopen, asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
data = fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1})
|
||||
data = fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1}, [])
|
||||
self.assertEqual(data, PAYLOAD)
|
||||
self.assertEqual(asked, [f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"])
|
||||
|
||||
def test_other_bytes_under_the_hash_are_refused(self):
|
||||
urlopen, _asked = _serving({fetch.SOFTWARE_HERITAGE: b"something else"})
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
data = fetch.step3b_software_heritage({"name": "x", "sha1": SHA1})
|
||||
data = fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}, [])
|
||||
self.assertIsNone(data)
|
||||
|
||||
def test_an_absent_file_is_not_counted_as_a_source_that_did_not_answer(self):
|
||||
urlopen, _asked = _serving({})
|
||||
fetch._UNANSWERED.clear()
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
self.assertIsNone(fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}))
|
||||
self.assertEqual(fetch._UNANSWERED, [])
|
||||
found = fetch.search({"name": "x", "sha1": SHA1}, fetch.SHA1_SOURCES)
|
||||
self.assertEqual(found, fetch.SearchResult(None, None, ()))
|
||||
|
||||
|
||||
class LookupBySha1(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.cwd = os.getcwd()
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
os.chdir(self.root)
|
||||
self.addCleanup(os.chdir, self.cwd)
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name)
|
||||
self.acquire = self.root / "tmp" / "acquire"
|
||||
|
||||
def test_a_found_file_goes_to_tmp_acquire_never_to_bios(self):
|
||||
urlopen, _asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
code = fetch.lookup_sha1s([SHA1.upper()], {"files": {}})
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual((self.root / "tmp" / "acquire" / SHA1).read_bytes(), PAYLOAD)
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
[record] = fetch.lookup_sha1s([SHA1.upper()], {"files": {}},
|
||||
acquire_dir=self.acquire)
|
||||
self.assertEqual((record.outcome, record.source), ("found", "software_heritage"))
|
||||
self.assertEqual((self.acquire / SHA1).read_bytes(), PAYLOAD)
|
||||
self.assertFalse((self.root / "bios").exists())
|
||||
self.assertIn("found in Software Heritage", out.getvalue())
|
||||
self.assertIn("found in Software Heritage", fetchtext.lookup_line(record))
|
||||
|
||||
def test_the_default_folder_is_under_the_repository(self):
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
self.assertEqual(fetch.ACQUIRE_DIR, REPO_ROOT / "tmp" / "acquire")
|
||||
|
||||
def test_a_held_file_is_named_and_not_fetched(self):
|
||||
urlopen, asked = _serving({})
|
||||
db = {"files": {SHA1: {"path": "bios/Commodore/Amiga/x.rom"}}}
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
code = fetch.lookup_sha1s([SHA1], db)
|
||||
code = fetchtext.report_lookups([SHA1], db, acquire_dir=self.acquire)
|
||||
self.assertEqual((code, asked), (0, []))
|
||||
self.assertIn("already held at bios/Commodore/Amiga/x.rom", out.getvalue())
|
||||
|
||||
@@ -97,10 +101,33 @@ class LookupBySha1(unittest.TestCase):
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as out, \
|
||||
contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
code = fetch.lookup_sha1s([SHA1, "not-a-hash"], {"files": {}})
|
||||
code = fetchtext.report_lookups([SHA1, "not-a-hash"], {"files": {}},
|
||||
acquire_dir=self.acquire)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn(f"{SHA1}: not found", out.getvalue())
|
||||
self.assertIn("not-a-hash: not a sha1", err.getvalue())
|
||||
self.assertEqual(out.getvalue(), f" {SHA1}: not found\n")
|
||||
self.assertEqual(err.getvalue(), " not-a-hash: not a sha1\n")
|
||||
|
||||
|
||||
class PlatformSearchLines(unittest.TestCase):
|
||||
"""The search returns records, the text module alone prints them."""
|
||||
|
||||
def test_a_file_kept_out_of_bios_says_why_before_where_it_went(self):
|
||||
from acquire.placement import Placement
|
||||
|
||||
record = fetch.FetchRecord(
|
||||
{"name": "neogeo.zip", "system": "snk-neogeo"}, "found", source="archive_org",
|
||||
placed=Placement("tmp/acquire/ab", kept_out=True, folders=("bios/A/", "bios/B/")))
|
||||
self.assertEqual(fetchtext.fetch_lines(record), [
|
||||
" No single bios/ folder for snk-neogeo (bios/A/, bios/B/): kept out of bios/",
|
||||
" [4] Found on archive.org, saved to: tmp/acquire/ab",
|
||||
])
|
||||
|
||||
def test_an_unanswered_source_makes_the_search_incomplete(self):
|
||||
record = fetch.FetchRecord({"name": "x", "system": "s"}, "incomplete",
|
||||
unanswered=("u: offline", "v: offline"))
|
||||
self.assertEqual(fetch.fetch_summary([record])["stats"]["errors"], 1)
|
||||
self.assertEqual(fetchtext.fetch_lines(record), [
|
||||
" [5] Search incomplete, 2 source(s) did not answer (first: u: offline)"])
|
||||
|
||||
|
||||
class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
|
||||
@@ -116,8 +143,6 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
|
||||
self.addCleanup(patcher.stop)
|
||||
upstream._exhausted_hosts.clear()
|
||||
self.addCleanup(upstream._exhausted_hosts.clear)
|
||||
fetch._UNANSWERED.clear()
|
||||
self.addCleanup(fetch._UNANSWERED.clear)
|
||||
|
||||
def test_a_stalled_read_is_recorded_and_the_search_goes_on(self):
|
||||
class _Stalled(_Answer):
|
||||
@@ -127,9 +152,11 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
|
||||
def urlopen(request, timeout=None):
|
||||
return _Stalled()
|
||||
|
||||
unanswered: list[str] = []
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
self.assertIsNone(fetch.step3_search_public_repos({"name": "x.bin", "sha1": SHA1}))
|
||||
self.assertEqual(len(fetch._UNANSWERED), len(fetch.PUBLIC_REPOS))
|
||||
self.assertIsNone(fetch.step3_search_public_repos(
|
||||
{"name": "x.bin", "sha1": SHA1}, unanswered))
|
||||
self.assertEqual(len(unanswered), len(fetch.PUBLIC_REPOS))
|
||||
|
||||
def test_a_rate_limit_is_waited_out(self):
|
||||
answers = [urllib.error.HTTPError("u", 429, "Too Many Requests", {}, None), PAYLOAD]
|
||||
@@ -141,8 +168,8 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
|
||||
return _Answer(answer)
|
||||
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
data = fetch.step3b_software_heritage({"name": "x", "sha1": SHA1})
|
||||
self.assertEqual((data, fetch._UNANSWERED), (PAYLOAD, []))
|
||||
found = fetch.search({"name": "x", "sha1": SHA1}, fetch.SHA1_SOURCES)
|
||||
self.assertEqual(found, fetch.SearchResult(PAYLOAD, "software_heritage", ()))
|
||||
|
||||
def test_the_destination_is_tried_when_the_name_is_too_large(self):
|
||||
asked: list[str] = []
|
||||
@@ -156,7 +183,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
|
||||
with mock.patch.object(fetch, "MAX_DOWNLOAD", 32), \
|
||||
mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
data = fetch.step3_search_public_repos(
|
||||
{"name": "x.bin", "destination": "sub/x.bin", "sha1": SHA1})
|
||||
{"name": "x.bin", "destination": "sub/x.bin", "sha1": SHA1}, [])
|
||||
self.assertEqual(data, PAYLOAD)
|
||||
self.assertEqual(len(asked), 2)
|
||||
|
||||
@@ -167,10 +194,6 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
|
||||
another path was a 404, and the file went to the issue asking the public
|
||||
for it while --sha1 found it."""
|
||||
|
||||
def setUp(self):
|
||||
fetch._UNANSWERED.clear()
|
||||
self.addCleanup(fetch._UNANSWERED.clear)
|
||||
|
||||
def _archive(self):
|
||||
import json
|
||||
|
||||
@@ -187,22 +210,23 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
|
||||
urlopen, asked = self._archive()
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
data = fetch.step4_search_archive_org(
|
||||
{"name": "scph1001.bin", "sha1": SHA1.upper()})
|
||||
{"name": "scph1001.bin", "sha1": SHA1.upper()}, [])
|
||||
self.assertEqual(data, PAYLOAD)
|
||||
self.assertNotIn("https://archive.org/download/psx-bios/scph1001.bin", asked)
|
||||
|
||||
def test_the_platform_search_and_the_sha1_search_agree(self):
|
||||
urlopen, _asked = self._archive()
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
by_platform = fetch.step4_search_archive_org({"name": "scph1001.bin", "sha1": SHA1})
|
||||
by_sha1 = fetch.archive_org_by_sha1(SHA1)
|
||||
by_platform = fetch.step4_search_archive_org(
|
||||
{"name": "scph1001.bin", "sha1": SHA1}, [])
|
||||
by_sha1 = fetch.archive_org_by_sha1(SHA1, [])
|
||||
self.assertEqual((by_platform, by_sha1), (PAYLOAD, PAYLOAD))
|
||||
|
||||
def test_a_declared_md5_still_has_to_hold(self):
|
||||
urlopen, _asked = self._archive()
|
||||
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
|
||||
data = fetch.step4_search_archive_org(
|
||||
{"name": "scph1001.bin", "sha1": SHA1, "md5": "f" * 32})
|
||||
{"name": "scph1001.bin", "sha1": SHA1, "md5": "f" * 32}, [])
|
||||
self.assertIsNone(data)
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import find_embedded
|
||||
from acquire import embedded
|
||||
from acquire import embedded, placement
|
||||
|
||||
ROM = bytes(random.Random(8039).randrange(256) for _ in range(2048))
|
||||
CRC = zlib.crc32(ROM)
|
||||
@@ -49,6 +49,7 @@ class Command(unittest.TestCase):
|
||||
|
||||
def run_cli(self, *argv: str) -> tuple[int, str]:
|
||||
with mock.patch.object(sys, "argv", ["find_embedded.py", *argv]), \
|
||||
mock.patch.object(placement, "ACQUIRE_DIR", self.root / "tmp" / "acquire"), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
code = find_embedded.main()
|
||||
return code, out.getvalue()
|
||||
|
||||
Reference in new issue
Block a user