refactor: move ten command helpers into packages

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 15:47:20 +01:00
1 parent 6d21a98342
commit 19681a3735
22 files changed
+218 -191

No files matched your search

+21
View File
@@ -319,3 +319,24 @@ def build_report(
"out_of_scope": out_of_scope,
}
return report
def print_missing(entry: dict, derived: dict[str, dict]) -> None:
"""One missing dump, with what derives it, reads it and holds it."""
label = entry.get("description") or entry["name"]
source = derived.get(entry.get("sha1", ""))
if source:
print(f" DERIVABLE {entry['name']} ({label}): {source['transform']} "
f"of {' + '.join(source['from'])}")
else:
print(f" MISSING {entry['name']} ({label}) sha1={entry.get('sha1')}")
for need in entry.get("needed_by", []):
print(f" needed by {need['emulator']} as {need['name']} "
f"({'required' if need['required'] else 'optional'}, "
f"matched by {need['by']})")
for hit in entry.get("romsets", []):
versions = hit["dats"][0] if len(hit["dats"]) == 1 else (
f"{hit['dats'][0]} to {hit['dats'][-1]}"
)
print(f" in {hit['source']} {hit['archive']} as "
f"{hit['member']} ({versions})")
+30
View File
@@ -0,0 +1,30 @@
"""The files that left database.json, read back through its git history."""
from __future__ import annotations
import json
import subprocess
from core.paths import REPO_ROOT
from model.retired import FIRST_ADDRESSED, merge, retired_between
def _git(*args: str) -> str:
return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True,
check=True).stdout
def backfill() -> dict[str, dict]:
"""Every sha1 that left database.json in the commits since content
addresses were published, with the day of the commit that dropped it."""
revisions = [line.split() for line in _git(
"log", "--reverse", "--format=%H %cs", f"{FIRST_ADDRESSED}^..HEAD", "--", "database.json",
).splitlines() if line.strip()]
records: dict[str, dict] = {}
previous: dict | None = None
for commit, day in revisions:
current = json.loads(_git("show", f"{commit}:database.json"))
if previous is not None:
records = merge(records, retired_between(previous, current, day), current)
previous = current
return records
+4
View File
@@ -141,3 +141,7 @@ def failure_excerpt(log: Path) -> list[str]:
if len(shown) > FAILURE_LINES:
lines.append(f"... {len(shown) - FAILURE_LINES} more lines in the log")
return lines
def say(line: str) -> None:
print(line, flush=True)
+1 -37
View File
@@ -17,47 +17,11 @@ then every count line.
from __future__ import annotations
import argparse
import re
import subprocess
import sys
from core.artifacts import write_text_atomic
from core.paths import REPO_ROOT
PAGE = REPO_ROOT / "wiki" / "reading-reports.md"
BLOCK = re.compile(
r"(<!-- generated: verify-retrodeck -->\n```\n)(.*?)(```\n<!-- /generated: verify-retrodeck -->)",
re.S)
# The count lines, in the order verify prints them.
COUNTS = (" Core files:", " Bundled with their emulator", " Core files held",
" Game data:", " Game data held", " Launcher reads", " Launcher records",
" No external files:", " Ground truth:", " ")
def excerpt(lines: list[str]) -> list[str]:
"""The lines of a verify run the page shows."""
kept = [lines[0]]
untested = next((line for line in lines if line.startswith(" UNTESTED")), None)
if untested:
kept.append(untested)
for index, line in enumerate(lines):
if line.startswith(" DISCREPANCY") and index + 1 < len(lines) \
and lines[index + 1].startswith(" "):
kept += [line, lines[index + 1]]
break
counts_from = next(i for i, line in enumerate(lines) if line.startswith(" Core files:"))
kept += [line for line in lines[counts_from:] if line.startswith(COUNTS)]
return kept
def run() -> list[str]:
proc = subprocess.run([sys.executable, str(REPO_ROOT / "scripts" / "verify.py"),
"--platform", "retrodeck"], capture_output=True, text=True,
cwd=REPO_ROOT, check=False)
lines = proc.stdout.splitlines()
if not lines or not lines[0].startswith("RetroDECK:"):
raise SystemExit(f"verify did not run: {proc.stderr[-300:]}")
return lines
from sitegen.reportexcerpt import BLOCK, PAGE, excerpt, run
def main() -> int:
+1 -26
View File
@@ -25,32 +25,7 @@ import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from sitegen.agents import INDEXNOW_FILE, INDEXNOW_KEY, SITE
HOST = "abdess.github.io"
# What one IndexNow request accepts.
MAX_URLS = 10_000
USER_AGENT = "retrobios-indexnow"
def live_digests(url: str = f"{SITE}digests.json") -> dict[str, str]:
"""The digests the live site serves. None yet (the first deploy that
writes them) is an empty map: every page is new."""
body = upstream.fetch_body(url, timeout=60, user_agent=USER_AGENT)
return {} if body is None else json.loads(body.decode("utf-8"))
def changed_urls(new: dict[str, str], old: dict[str, str]) -> list[str]:
"""Pages added, changed or removed between two digest maps."""
return sorted(url for url in new.keys() | old.keys() if new.get(url) != old.get(url))
def payload(urls: list[str]) -> dict:
if len(urls) > MAX_URLS:
raise SystemExit(f"error: {len(urls)} changed pages, one request takes {MAX_URLS}")
return {"host": HOST, "key": INDEXNOW_KEY, "keyLocation": f"{SITE}{INDEXNOW_FILE}",
"urlList": urls}
from sitegen.indexnow import changed_urls, live_digests, payload
def main() -> int:
+10
View File
@@ -577,3 +577,13 @@ def refresh_all(
forget_data_dir_index()
return results
def summarize(outcomes: dict[str, bool | None], dry_run: bool) -> str:
"""One closing line: how many entries changed, were current, failed."""
refreshed = sum(1 for o in outcomes.values() if o is True)
current = sum(1 for o in outcomes.values() if o is False)
failed = sum(1 for o in outcomes.values() if o is None)
verb = "would refresh" if dry_run else "refreshed"
line = f"{len(outcomes)} entries: {refreshed} {verb}, {current} up to date"
return f"{line}, {failed} failed" if failed else line
+9
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import argparse
import io
import re
import struct
@@ -304,3 +305,11 @@ def split_directory(directory: Path, limit: int = ASSET_LIMIT) -> list[Path]:
for path in sorted(Path(directory).glob(f"*{PACK_SUFFIX}")):
published.extend(split_pack(path, limit))
return published
def parse_size(text: str) -> int:
"""A byte count written with an optional K, M or G suffix."""
match = re.fullmatch(r"(\d+)([KMG]?)", text.strip().upper())
if not match:
raise argparse.ArgumentTypeError(f"not a size: {text}")
return int(match[1]) * 1024 ** " KMG".index(match[2] or " ")
+2 -22
View File
@@ -35,31 +35,11 @@ from acquire.provenance import (
build_report,
distinct_missing,
dump_identity,
print_missing,
profile_needs,
)
def _print_missing(entry: dict, derived: dict[str, dict]) -> None:
"""One missing dump, with what derives it, reads it and holds it."""
label = entry.get("description") or entry["name"]
source = derived.get(entry.get("sha1", ""))
if source:
print(f" DERIVABLE {entry['name']} ({label}): {source['transform']} "
f"of {' + '.join(source['from'])}")
else:
print(f" MISSING {entry['name']} ({label}) sha1={entry.get('sha1')}")
for need in entry.get("needed_by", []):
print(f" needed by {need['emulator']} as {need['name']} "
f"({'required' if need['required'] else 'optional'}, "
f"matched by {need['by']})")
for hit in entry.get("romsets", []):
versions = hit["dats"][0] if len(hit["dats"]) == 1 else (
f"{hit['dats'][0]} to {hit['dats'][-1]}"
)
print(f" in {hit['source']} {hit['archive']} as "
f"{hit['member']} ({versions})")
def main() -> int:
parser = argparse.ArgumentParser(allow_abbrev=False, description="Dump-catalog coverage report")
add_repo_inputs(parser, "db")
@@ -140,7 +120,7 @@ def main() -> int:
if args.missing:
# A dump an emulator reads comes first: it fills a hole in a pack.
for entry in sorted(data["missing"], key=lambda e: not e.get("needed_by")):
_print_missing(entry, derived)
print_missing(entry, derived)
total_missing = distinct_missing(report)
if total_missing:
+1 -11
View File
@@ -20,17 +20,7 @@ from model.cliargs import platform_arg, require_platform
from model.registry import data_dir_registry_at
from core.paths import DATA_DIRS_FILE
from packs.datadirs import log, refresh_all, refresh_entry
def summarize(outcomes: dict[str, bool | None], dry_run: bool) -> str:
"""One closing line: how many entries changed, were current, failed."""
refreshed = sum(1 for o in outcomes.values() if o is True)
current = sum(1 for o in outcomes.values() if o is False)
failed = sum(1 for o in outcomes.values() if o is None)
verb = "would refresh" if dry_run else "refreshed"
line = f"{len(outcomes)} entries: {refreshed} {verb}, {current} up to date"
return f"{line}, {failed} failed" if failed else line
from packs.datadirs import log, refresh_all, refresh_entry, summarize
def main() -> None:
+1 -42
View File
@@ -19,48 +19,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from core.cli import add_repo_inputs
from model.database import load_database
from model.profiles import load_emulator_profiles
from resolve.regionaudit import build_report
LIMITS = """Limits, read before trusting any line below.
TOSEC's country field is the country of ORIGIN, not the regional variant
(TOSEC Naming Convention v4, p.12). A Korean MSX ROM published by Microsoft
US is tagged (US). TOSEC names are therefore NOT read here.
Redump DATs carry no region at all: it exists in the redump.org database but
is never exported, so a Redump entry contributes nothing.
Only No-Intro filename tokens are usable, and only for the fraction of repo
files that carry one. Everything else is silent, not clean.
The emulator source decides. A disagreement is a prompt to reread the code,
never a correction to apply on its own.
"""
def print_report(report: dict) -> None:
print(LIMITS)
print(
f"repo files: {report['repo_files']} "
f"with a usable No-Intro region token: {report['catalog_files']}"
)
print(
f"declared region: values -> agree {report['agree']}, "
f"disagree {report['disagree']}, no catalogue entry {report['unchecked']}"
)
if report["vocabulary"]:
print("\ncatalogue vocabulary present in this collection:")
for slug, count in report["vocabulary"].items():
print(f" {count:5d} {slug}")
if not report["conflicts"]:
print("\nNo disagreement.")
return
print("\nDISAGREEMENTS (reread the emulator source, do not apply blindly):\n")
for c in report["conflicts"]:
print(f" {c['emulator']}: {c['file']}")
print(f" profile: {c['profile']}")
print(f" catalogue: {c['catalog']} ({c['dat_name']})")
from resolve.regionaudit import build_report, print_report
def main() -> int:
+41
View File
@@ -103,3 +103,44 @@ def build_report(profiles: dict, db: dict) -> dict:
"vocabulary": dict(vocabulary.most_common()),
"conflicts": conflicts,
}
LIMITS = """Limits, read before trusting any line below.
TOSEC's country field is the country of ORIGIN, not the regional variant
(TOSEC Naming Convention v4, p.12). A Korean MSX ROM published by Microsoft
US is tagged (US). TOSEC names are therefore NOT read here.
Redump DATs carry no region at all: it exists in the redump.org database but
is never exported, so a Redump entry contributes nothing.
Only No-Intro filename tokens are usable, and only for the fraction of repo
files that carry one. Everything else is silent, not clean.
The emulator source decides. A disagreement is a prompt to reread the code,
never a correction to apply on its own.
"""
def print_report(report: dict) -> None:
print(LIMITS)
print(
f"repo files: {report['repo_files']} "
f"with a usable No-Intro region token: {report['catalog_files']}"
)
print(
f"declared region: values -> agree {report['agree']}, "
f"disagree {report['disagree']}, no catalogue entry {report['unchecked']}"
)
if report["vocabulary"]:
print("\ncatalogue vocabulary present in this collection:")
for slug, count in report["vocabulary"].items():
print(f" {count:5d} {slug}")
if not report["conflicts"]:
print("\nNo disagreement.")
return
print("\nDISAGREEMENTS (reread the emulator source, do not apply blindly):\n")
for c in report["conflicts"]:
print(f" {c['emulator']}: {c['file']}")
print(f" profile: {c['profile']}")
print(f" catalogue: {c['catalog']} ({c['dat_name']})")
+2 -24
View File
@@ -8,8 +8,6 @@ Usage:
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
@@ -18,28 +16,8 @@ from core.cli import run_cli
from core.artifacts import write_if_changed
from core.paths import DB_FILE, REPO_ROOT
from model.database import load_database
from model.retired import FIRST_ADDRESSED, RETIRED_FILE, dump, merge, retired_between
def _git(*args: str) -> str:
return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True,
check=True).stdout
def backfill() -> dict[str, dict]:
"""Every sha1 that left database.json in the commits since content
addresses were published, with the day of the commit that dropped it."""
revisions = [line.split() for line in _git(
"log", "--reverse", "--format=%H %cs", f"{FIRST_ADDRESSED}^..HEAD", "--", "database.json",
).splitlines() if line.strip()]
records: dict[str, dict] = {}
previous: dict | None = None
for commit, day in revisions:
current = json.loads(_git("show", f"{commit}:database.json"))
if previous is not None:
records = merge(records, retired_between(previous, current, day), current)
previous = current
return records
from model.retired import FIRST_ADDRESSED, RETIRED_FILE, dump, merge
from collection.retiredhistory import backfill
def main() -> int:
+1 -4
View File
@@ -36,14 +36,11 @@ from devtools.testrunner import (
rerun_crashed,
run_all,
save_durations,
say,
weight,
)
def say(line: str) -> None:
print(line, flush=True)
def main() -> int:
parser = argparse.ArgumentParser(allow_abbrev=False,
description=__doc__.split("\n\n", 1)[0])
+32
View File
@@ -0,0 +1,32 @@
"""The pages a deploy changes, as the request body IndexNow takes."""
from __future__ import annotations
import json
from core import upstream
from sitegen.agents import INDEXNOW_FILE, INDEXNOW_KEY, SITE
HOST = "abdess.github.io"
# What one IndexNow request accepts.
MAX_URLS = 10_000
USER_AGENT = "retrobios-indexnow"
def live_digests(url: str = f"{SITE}digests.json") -> dict[str, str]:
"""The digests the live site serves. None yet (the first deploy that
writes them) is an empty map: every page is new."""
body = upstream.fetch_body(url, timeout=60, user_agent=USER_AGENT)
return {} if body is None else json.loads(body.decode("utf-8"))
def changed_urls(new: dict[str, str], old: dict[str, str]) -> list[str]:
"""Pages added, changed or removed between two digest maps."""
return sorted(url for url in new.keys() | old.keys() if new.get(url) != old.get(url))
def payload(urls: list[str]) -> dict:
if len(urls) > MAX_URLS:
raise SystemExit(f"error: {len(urls)} changed pages, one request takes {MAX_URLS}")
return {"host": HOST, "key": INDEXNOW_KEY, "keyLocation": f"{SITE}{INDEXNOW_FILE}",
"urlList": urls}
+44
View File
@@ -0,0 +1,44 @@
"""The lines of a verify run that wiki/reading-reports.md quotes."""
from __future__ import annotations
import re
import subprocess
import sys
from core.paths import REPO_ROOT
PAGE = REPO_ROOT / "wiki" / "reading-reports.md"
BLOCK = re.compile(
r"(<!-- generated: verify-retrodeck -->\n```\n)(.*?)(```\n<!-- /generated: verify-retrodeck -->)",
re.S)
# The count lines, in the order verify prints them.
COUNTS = (" Core files:", " Bundled with their emulator", " Core files held",
" Game data:", " Game data held", " Launcher reads", " Launcher records",
" No external files:", " Ground truth:", " ")
def excerpt(lines: list[str]) -> list[str]:
"""The lines of a verify run the page shows."""
kept = [lines[0]]
untested = next((line for line in lines if line.startswith(" UNTESTED")), None)
if untested:
kept.append(untested)
for index, line in enumerate(lines):
if line.startswith(" DISCREPANCY") and index + 1 < len(lines) \
and lines[index + 1].startswith(" "):
kept += [line, lines[index + 1]]
break
counts_from = next(i for i, line in enumerate(lines) if line.startswith(" Core files:"))
kept += [line for line in lines[counts_from:] if line.startswith(COUNTS)]
return kept
def run() -> list[str]:
proc = subprocess.run([sys.executable, str(REPO_ROOT / "scripts" / "verify.py"),
"--platform", "retrodeck"], capture_output=True, text=True,
cwd=REPO_ROOT, check=False)
lines = proc.stdout.splitlines()
if not lines or not lines[0].startswith("RetroDECK:"):
raise SystemExit(f"verify did not run: {proc.stderr[-300:]}")
return lines
+2 -10
View File
@@ -20,20 +20,12 @@ Usage:
from __future__ import annotations
import argparse
import re
import sys
import zipfile
from pathlib import Path
from core.artifacts import ArtifactLockBusy, artifact_lock
from packs.parts import ASSET_LIMIT, split_directory, split_pack
def _size(text: str) -> int:
match = re.fullmatch(r"(\d+)([KMG]?)", text.strip().upper())
if not match:
raise argparse.ArgumentTypeError(f"not a size: {text}")
return int(match[1]) * 1024 ** " KMG".index(match[2] or " ")
from packs.parts import ASSET_LIMIT, parse_size, split_directory, split_pack
def main() -> int:
@@ -43,7 +35,7 @@ def main() -> int:
)
parser.add_argument("target", type=Path, help="a pack, or a directory of packs")
parser.add_argument(
"--max-size", type=_size, default=ASSET_LIMIT, metavar="SIZE",
"--max-size", type=parse_size, default=ASSET_LIMIT, metavar="SIZE",
help="a part stays under this many bytes (K, M, G suffixes, default 2G)",
)
args = parser.parse_args()
+4
View File
@@ -40,6 +40,8 @@ COMMANDS = {
),
"refresh_data_dirs.py": ("packs/datadirs.py",),
"split_pack.py": ("packs/parts.py",),
"retired_files.py": ("model/retired.py", "collection/retiredhistory.py"),
"region_audit.py": ("resolve/regionaudit.py",),
"dedup.py": (
"model/nodedup.py", "collection/dedup.py", "collection/duplicates.py",
"collection/clonemap.py",
@@ -78,6 +80,8 @@ COMMANDS = {
"validate_site.py": ("sitegen/validate.py",),
"site_insights.py": ("sitegen/insights.py",),
"generate_readme.py": ("sitegen/readme.py",),
"indexnow.py": ("sitegen/indexnow.py",),
"generate_report_excerpt.py": ("sitegen/reportexcerpt.py",),
"romset_recipes.py": (
"romrecipes/romsets.py", "romrecipes/pool.py", "romrecipes/pins.py",
"romrecipes/identify.py", "romrecipes/ledger.py", "romrecipes/members.py",
+1 -3
View File
@@ -289,7 +289,6 @@ class RestoreSkipsDownloadsInProgress(unittest.TestCase):
"""A scratch file another run is still writing is neither hashed nor read."""
def test_a_scratch_promoted_mid_scan_does_not_stop_the_restore(self) -> None:
import restore_large_files
from release import restore
with tempfile.TemporaryDirectory() as tmp:
@@ -307,8 +306,7 @@ class RestoreSkipsDownloadsInProgress(unittest.TestCase):
os.replace(scratch, cache / "big.bin")
return found
with mock.patch.object(restore_large_files.os.path, "isfile",
side_effect=check_then_promote):
with mock.patch.object(os.path, "isfile", side_effect=check_then_promote):
index = restore.index_cache(str(cache))
self.assertNotIn(str(scratch), index.values())
self.assertIn(str(cache / "done.bin"), index.values())
+4 -4
View File
@@ -7187,15 +7187,15 @@ class TheEventSchemaFileIsEventKeys(unittest.TestCase):
generator.build_schema()
def test_the_check_command_fails_on_a_stale_file(self):
import generate_event_schema as generator
import generate_event_schema as command
scratch = scratch_dir(self) / "events.schema.json"
scratch.write_text("{}\n", encoding="utf-8")
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(generator.main(["--check", "--output", str(scratch)]), 1)
self.assertEqual(generator.main(["--output", str(scratch)]), 0)
self.assertEqual(generator.main(["--check", "--output", str(scratch)]), 0)
self.assertEqual(command.main(["--check", "--output", str(scratch)]), 1)
self.assertEqual(command.main(["--output", str(scratch)]), 0)
self.assertEqual(command.main(["--check", "--output", str(scratch)]), 0)
class TheInstallerPageIsWrittenFromTheCode(unittest.TestCase):
+2 -3
View File
@@ -20,7 +20,6 @@ import zipfile
from pathlib import Path
from unittest import mock
import refresh_data_dirs as rdd
from packs import datadirs
from model.registry import load_data_dir_registry, load_versions
from packs.archive import Placed
@@ -313,11 +312,11 @@ class DryRunReport(unittest.TestCase):
def test_a_run_ends_on_its_counts(self):
self.assertEqual(
rdd.summarize({"a": True, "b": False, "c": False}, dry_run=True),
datadirs.summarize({"a": True, "b": False, "c": False}, dry_run=True),
"3 entries: 1 would refresh, 2 up to date",
)
self.assertEqual(
rdd.summarize({"a": True, "b": None}, dry_run=False),
datadirs.summarize({"a": True, "b": None}, dry_run=False),
"2 entries: 1 refreshed, 0 up to date, 1 failed",
)
+4 -4
View File
@@ -7,7 +7,7 @@ import tests
import unittest
import generate_report_excerpt
from sitegen import reportexcerpt
RUN = [
"RetroDECK: 9/10 OK, 1 untested [md5]",
@@ -26,12 +26,12 @@ RUN = [
class TheExcerptIsTheRun(unittest.TestCase):
def test_one_entry_of_each_shape_then_every_count(self):
self.assertEqual(generate_report_excerpt.excerpt(RUN), [
self.assertEqual(reportexcerpt.excerpt(RUN), [
RUN[0], RUN[1], RUN[3], RUN[4], RUN[7], RUN[8], RUN[9], RUN[10]])
def test_the_page_carries_the_block(self):
text = generate_report_excerpt.PAGE.read_text(encoding="utf-8")
self.assertIsNotNone(generate_report_excerpt.BLOCK.search(text))
text = reportexcerpt.PAGE.read_text(encoding="utf-8")
self.assertIsNotNone(reportexcerpt.BLOCK.search(text))
if __name__ == "__main__":
+1 -1
View File
@@ -13,8 +13,8 @@ import tempfile
import unittest
from pathlib import Path
import indexnow
from sitegen import agents as siteagents
from sitegen import indexnow
from sitegen import pagemarkdown
ROOT = Path(__file__).resolve().parent.parent