mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-27 11:58:53 -06:00
refactor: public names for cross-module reads
This commit is contained in:
1 parent
f371790dc6
commit
3853ca2f1c
254 files changed
+2955
-2969
No files matched your search
+11
-11
@@ -5,14 +5,14 @@ from __future__ import annotations
|
||||
import urllib.parse
|
||||
from collections.abc import Callable
|
||||
|
||||
from model.collection import _group_by_manufacturer, _slug
|
||||
from model.collection import group_by_manufacturer, manufacturer_slug
|
||||
from model.systemnames import system_name
|
||||
from sitegen.config import SITE_URL
|
||||
from sitegen.lookup import _hash_values, _site_path
|
||||
from sitegen.lookup import sorted_hash_values, site_path
|
||||
from sitegen.render import console_href
|
||||
|
||||
|
||||
def _sha1_by_path(db: dict | None) -> dict[str, str]:
|
||||
def sha1_index_by_path(db: dict | None) -> dict[str, str]:
|
||||
return {str(e.get("path", "")): sha1 for sha1, e in ((db or {}).get("files") or {}).items()}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
|
||||
"""
|
||||
from sitegen.render import card_page, system_ids, system_section
|
||||
|
||||
sha1_by_path = _sha1_by_path(db)
|
||||
sha1_by_path = sha1_index_by_path(db)
|
||||
files = db.get("files") or {}
|
||||
by_md5 = (db.get("indexes") or {}).get("by_md5") or {}
|
||||
held: dict[str, set[str]] = {}
|
||||
@@ -48,13 +48,13 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
|
||||
ids = ([str(entry["system"])] if entry.get("system")
|
||||
else [str(s) for s in entry.get("systems") or []] or
|
||||
(own if len(own) == 1 else []))
|
||||
found = {v for v in _hash_values(entry.get("sha1")) if v in files}
|
||||
for md5 in _hash_values(entry.get("md5")):
|
||||
found = {v for v in sorted_hash_values(entry.get("sha1")) if v in files}
|
||||
for md5 in sorted_hash_values(entry.get("md5")):
|
||||
match = by_md5.get(md5)
|
||||
found.update([match] if isinstance(match, str) else match or [])
|
||||
for sys_id in ids:
|
||||
held.setdefault(sys_id, set()).update(found)
|
||||
manufacturers = {_slug(mfr): mfr for mfr in _group_by_manufacturer(db)}
|
||||
manufacturers = {manufacturer_slug(mfr): mfr for mfr in group_by_manufacturer(db)}
|
||||
base = urllib.parse.urlsplit(SITE_URL).path
|
||||
items = []
|
||||
for sys_id in sorted(system_ids(profiles, [c["config"] for c in coverages.values()])):
|
||||
@@ -65,12 +65,12 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
|
||||
name = sys_id
|
||||
sha1s = sorted(held.get(sys_id, set()) & files.keys())
|
||||
manufacturer = manufacturers.get(section[0], "") if section else ""
|
||||
url = _site_path(console_href(*section)) if section else None
|
||||
url = site_path(console_href(*section)) if section else None
|
||||
if url is None and sha1s:
|
||||
manufacturer, url = _first_file_place(sys_id, sha1s, files, profiles, card_page)
|
||||
# The id's JSON document: api/v1/systems/ is keyed by the manufacturer
|
||||
# page, and sony-playstation.json answered 404.
|
||||
holder = section[0] if section else _slug(manufacturer) if manufacturer else ""
|
||||
holder = section[0] if section else manufacturer_slug(manufacturer) if manufacturer else ""
|
||||
api = f"{base}api/v1/systems/{holder}.json" if holder else None
|
||||
items.append({"id": sys_id, "name": name, "manufacturer": manufacturer,
|
||||
"url": url, "api": api, "sha1": sha1s})
|
||||
@@ -87,11 +87,11 @@ def _first_file_place(
|
||||
parts = str(files[sha1].get("path", "")).split("/")
|
||||
if len(parts) >= 3 and parts[0] == "bios":
|
||||
page = card_page("/".join(parts), sha1)
|
||||
return parts[1], _site_path(f"systems/{page}.md#sha1-{sha1[:12]}")
|
||||
return parts[1], site_path(f"systems/{page}.md#sha1-{sha1[:12]}")
|
||||
for key in sorted(profiles):
|
||||
profile = profiles[key]
|
||||
if profile.get("type") != "alias" and profile.get("role") != "test" and sys_id in (profile.get("systems") or []):
|
||||
return "", _site_path(f"emulators/{key}.md")
|
||||
return "", site_path(f"emulators/{key}.md")
|
||||
return "", None
|
||||
|
||||
|
||||
|
||||
+62
-61
@@ -14,7 +14,7 @@ from pathlib import Path
|
||||
from romrecipes import ledger
|
||||
from model import releaserecord
|
||||
from model import siteinputs
|
||||
from model.collection import _group_by_manufacturer, _slug
|
||||
from model.collection import group_by_manufacturer, manufacturer_slug
|
||||
from model.composition import compute_composition
|
||||
from model.database import load_database
|
||||
from model.dumpcatalog import load_provenance_snapshots
|
||||
@@ -38,11 +38,12 @@ from sitegen import (
|
||||
steps as sitesteps,
|
||||
wanted as sitewanted,
|
||||
)
|
||||
from sitegen.cards import _wanted_link, system_install_choices, tables_out_of_search
|
||||
from sitegen.config import GENERATED_DIRS, PUBLIC_DIRS, REPO_URL, _REPO_ROOT, _timestamp, yaml
|
||||
from sitegen.cards import wanted_link, system_install_choices, tables_out_of_search
|
||||
from sitegen.config import GENERATED_DIRS, PUBLIC_DIRS, REPO_URL, data_timestamp, yaml
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.crossref import generate_cross_reference
|
||||
from sitegen.dataexports import (
|
||||
_source_commit,
|
||||
source_commit,
|
||||
build_emulator_gap_report,
|
||||
generate_data_exports,
|
||||
generate_stats,
|
||||
@@ -50,22 +51,22 @@ from sitegen.dataexports import (
|
||||
write_single_item,
|
||||
)
|
||||
from sitegen.datapage import generate_data_page
|
||||
from sitegen.decorate import SEARCH_DEMOTED, _front_matter, decorate_markdown_pages
|
||||
from sitegen.decorate import SEARCH_DEMOTED, front_matter, decorate_markdown_pages
|
||||
from sitegen.descriptions import PAGE_DATA, PART_PAGES
|
||||
from sitegen.emulatorcards import (
|
||||
ARCHIVE_RECIPES_PAGE,
|
||||
ROMSET_FAQ_PAGE,
|
||||
_DATA_MEMBERS,
|
||||
DATA_MEMBERS,
|
||||
emulator_setups,
|
||||
with_archive_counts,
|
||||
with_romset_table,
|
||||
)
|
||||
from sitegen.emulatorpage import (
|
||||
_DATA_READERS,
|
||||
_DATA_REVISIONS,
|
||||
_EMULATOR_SETUPS,
|
||||
_MEASUREMENT_ITEMS,
|
||||
_availability_check,
|
||||
DATA_READERS,
|
||||
DATA_REVISIONS,
|
||||
EMULATOR_SETUPS,
|
||||
MEASUREMENT_ITEMS,
|
||||
availability_check,
|
||||
emulator_pages,
|
||||
emulator_parts,
|
||||
plan_emulator_pages,
|
||||
@@ -83,12 +84,12 @@ from sitegen.lookup import (
|
||||
generate_files_page,
|
||||
page_data_directories,
|
||||
)
|
||||
from sitegen.nav import _overview_anchors, generate_nav
|
||||
from sitegen.parts import PUBLISHED_PARTS_FILE, _published_parts, record_parts
|
||||
from sitegen.places import _system_pages_from_data
|
||||
from sitegen.platformfiles import _EXPORTED
|
||||
from sitegen.nav import overview_anchors, generate_nav
|
||||
from sitegen.parts import PUBLISHED_PARTS_FILE, load_published_parts, record_parts
|
||||
from sitegen.places import system_pages_from_data
|
||||
from sitegen.platformfiles import EXPORTED
|
||||
from sitegen.platformindex import SETUP_TABLE_PAGE, generate_platform_index, with_setup_table
|
||||
from sitegen.platformpage import _own_list_only, generate_platform_page
|
||||
from sitegen.platformpage import own_list_only, generate_platform_page
|
||||
from sitegen.provenance import generate_provenance_page, load_derivable
|
||||
from sitegen.publish import write_release_advertised
|
||||
from sitegen.readme import platform_coverages
|
||||
@@ -100,9 +101,9 @@ from sitegen.reference import (
|
||||
)
|
||||
from sitegen.render import (
|
||||
WIKI_SRC_DIR,
|
||||
_icon_name,
|
||||
_pct,
|
||||
_system_page_map,
|
||||
console_icon_name,
|
||||
percent_text,
|
||||
system_page_map,
|
||||
prime_system_icons,
|
||||
reset_console_pages,
|
||||
set_system_page_map,
|
||||
@@ -118,8 +119,8 @@ from sitegen.structured import (
|
||||
from sitegen.systempages import arcade_board_sections, system_pages
|
||||
from sitegen.systemsindex import generate_systems_index
|
||||
from sitegen.versions import compute_stats
|
||||
from sitegen.whichpack import _build_emulator_file_index, _build_file_consumers, generate_which_pack
|
||||
from sitegen.write import _record, _sweep_generated, _sweep_top_pages, write_if_changed
|
||||
from sitegen.whichpack import build_emulator_file_index, build_file_consumers, generate_which_pack
|
||||
from sitegen.write import record_written, sweep_generated, sweep_top_pages, write_if_changed
|
||||
|
||||
|
||||
def _write_public_assets(docs: Path, public: Path) -> None:
|
||||
@@ -133,9 +134,9 @@ def _write_public_assets(docs: Path, public: Path) -> None:
|
||||
# the sitemap instead (Starlight's head links it).
|
||||
(public / "robots.txt").unlink(missing_ok=True)
|
||||
# The one-line commands' bootstraps, at the site's root.
|
||||
sitebootstrap.write_bootstraps(public, _REPO_ROOT)
|
||||
sitebootstrap.write_bootstraps(public, REPO_ROOT)
|
||||
# The handheld launchers, built from the same commit (sitehandheld).
|
||||
sitehandheld.write_launchers(public, _REPO_ROOT)
|
||||
sitehandheld.write_launchers(public, REPO_ROOT)
|
||||
|
||||
images_dest = public / "assets" / "images"
|
||||
images_dest.mkdir(parents=True, exist_ok=True)
|
||||
@@ -195,7 +196,7 @@ class _SiteRun:
|
||||
def _load_site_run(args: argparse.Namespace, db: dict, docs: Path, public: Path) -> _SiteRun:
|
||||
"""The registry, the coverage of every platform and the profiles."""
|
||||
from model.registry import load_data_dir_registry
|
||||
from packs.crossref import _build_supplemental_index
|
||||
from packs.crossref import build_supplemental_index
|
||||
|
||||
registry = _load_registry(args.platforms_dir)
|
||||
|
||||
@@ -204,14 +205,14 @@ def _load_site_run(args: argparse.Namespace, db: dict, docs: Path, public: Path)
|
||||
)
|
||||
|
||||
data_registry = load_data_dir_registry(args.platforms_dir)
|
||||
suppl_names = _build_supplemental_index()
|
||||
suppl_names = build_supplemental_index()
|
||||
|
||||
print("Computing platform coverage...")
|
||||
coverages = platform_coverages(
|
||||
sorted(platform_names), args.platforms_dir, db, data_registry,
|
||||
emulators_dir=args.emulators_dir, db_path=args.db,
|
||||
report=lambda _name, cov: print(
|
||||
f" {cov['platform']}: {cov['present']}/{cov['total']} ({_pct(cov['present'], cov['total'])})"
|
||||
f" {cov['platform']}: {cov['present']}/{cov['total']} ({percent_text(cov['present'], cov['total'])})"
|
||||
),
|
||||
)
|
||||
|
||||
@@ -222,7 +223,7 @@ def _load_site_run(args: argparse.Namespace, db: dict, docs: Path, public: Path)
|
||||
f" {len(profiles)} profiles ({unique_count} unique, {len(profiles) - unique_count} aliases)"
|
||||
)
|
||||
|
||||
consumers = _build_file_consumers(db, coverages, profiles)
|
||||
consumers = build_file_consumers(db, coverages, profiles)
|
||||
return _SiteRun(args, db, docs, public, registry, platform_names, data_registry,
|
||||
suppl_names, coverages, profiles, consumers)
|
||||
|
||||
@@ -259,7 +260,7 @@ def _write_system_pages(run: _SiteRun) -> None:
|
||||
print("Generating system pages...")
|
||||
|
||||
prime_system_icons({
|
||||
_icon_name(mfr, console)
|
||||
console_icon_name(mfr, console)
|
||||
for mfr, consoles in manufacturers.items()
|
||||
for console in consoles
|
||||
})
|
||||
@@ -290,9 +291,9 @@ def _write_system_pages(run: _SiteRun) -> None:
|
||||
public / "api" / "v1" / "systems" / f"{slug}.json", "systems",
|
||||
# The published data keeps the collection's folders.
|
||||
system_export_item(slug, mfr, manufacturers[mfr]),
|
||||
str(db.get("generated_at") or _timestamp()), _source_commit(),
|
||||
str(db.get("generated_at") or data_timestamp()), source_commit(),
|
||||
)
|
||||
clash = split_system_stems() & {_slug(m) for m in manufacturers}
|
||||
clash = split_system_stems() & {manufacturer_slug(m) for m in manufacturers}
|
||||
if clash:
|
||||
raise RuntimeError(f"a console page takes a manufacturer's address: {sorted(clash)}")
|
||||
|
||||
@@ -302,12 +303,12 @@ def _write_measurements(run: _SiteRun) -> sitemeasurements.Built:
|
||||
print("Compiling the measurements...")
|
||||
measured = sitemeasurements.build(
|
||||
run.public, emulators_dir=Path(run.args.emulators_dir), repo=REPO_URL,
|
||||
system_names={sys_id: system_name(sys_id) for sys_id in sorted(set(_system_page_map))},
|
||||
system_names={sys_id: system_name(sys_id) for sys_id in sorted(set(system_page_map))},
|
||||
)
|
||||
for path in measured.paths:
|
||||
_record(path)
|
||||
_MEASUREMENT_ITEMS.clear()
|
||||
_MEASUREMENT_ITEMS.update(sitemeasurements.by_emulator(measured.index))
|
||||
record_written(path)
|
||||
MEASUREMENT_ITEMS.clear()
|
||||
MEASUREMENT_ITEMS.update(sitemeasurements.by_emulator(measured.index))
|
||||
print(f" {measured.index['records']} records, {measured.index['count']} tests")
|
||||
write_if_changed(str(run.docs / sitemeasurements.EXPLORER_PAGE),
|
||||
sitemeasurements.generate_explorer_page(measured.index) + reference_next())
|
||||
@@ -331,7 +332,7 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
|
||||
"""The platform pages and the pages their long lists went to. Returns
|
||||
the published parts, each part's page with the anchor it came from."""
|
||||
docs, coverages = run.docs, run.coverages
|
||||
emulator_files = _build_emulator_file_index(run.profiles)
|
||||
emulator_files = build_emulator_file_index(run.profiles)
|
||||
print("Generating platform pages...")
|
||||
write_if_changed(
|
||||
str(docs / "platforms" / "index.md"),
|
||||
@@ -339,7 +340,7 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
|
||||
)
|
||||
if HANDHELD_GUIDE:
|
||||
write_if_changed(str(docs / HANDHELD_GUIDE.path), generate_handheld_guide(HANDHELD_GUIDE))
|
||||
published_parts = _published_parts()
|
||||
published_parts = load_published_parts()
|
||||
for name, cov in coverages.items():
|
||||
# The emulators this platform runs, not every one of the system.
|
||||
runs = resolve_platform_cores(cov["config"], run.profiles)
|
||||
@@ -364,7 +365,7 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
|
||||
# of the index: the title alone, found again on the setup's page
|
||||
# and the console's, is all the search held of them.
|
||||
SEARCH_DEMOTED.add(f"platforms/{stem}.md")
|
||||
front = _front_matter(page)
|
||||
front = front_matter(page)
|
||||
if front:
|
||||
page = page[page.find("\n---\n", 4) + 5:].lstrip("\n")
|
||||
front.update(level="reference", search="exclude",
|
||||
@@ -379,17 +380,17 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
|
||||
def _record_data_trees(profiles: dict) -> None:
|
||||
"""The data directories: their members, revisions and readers, and the
|
||||
pages their member lists go to."""
|
||||
_DATA_MEMBERS.update(data_directory_members())
|
||||
_DATA_REVISIONS.update(data_directory_revisions())
|
||||
DATA_MEMBERS.update(data_directory_members())
|
||||
DATA_REVISIONS.update(data_directory_revisions())
|
||||
for key in sorted(profiles):
|
||||
if profiles[key].get("type") == "alias" or profiles[key].get("role") == "test":
|
||||
continue
|
||||
display = str(profiles[key].get("emulator", key))
|
||||
for tree in page_data_directories(key, profiles):
|
||||
readers = _DATA_READERS.setdefault(str(tree.get("ref", "")), [])
|
||||
readers = DATA_READERS.setdefault(str(tree.get("ref", "")), [])
|
||||
if (key, display) not in readers:
|
||||
readers.append((key, display))
|
||||
for ref, members in _DATA_MEMBERS.items():
|
||||
for ref, members in DATA_MEMBERS.items():
|
||||
for stem, _names in data_tree_pages(ref, members):
|
||||
PART_PAGES.add(f"emulators/{stem}.md")
|
||||
|
||||
@@ -398,7 +399,7 @@ def _write_emulator_pages(run: _SiteRun) -> None:
|
||||
"""The emulator index, and each emulator's page and API item."""
|
||||
profiles = run.profiles
|
||||
print("Generating emulator pages...")
|
||||
_EMULATOR_SETUPS.update(emulator_setups(run.coverages, profiles))
|
||||
EMULATOR_SETUPS.update(emulator_setups(run.coverages, profiles))
|
||||
_record_data_trees(profiles)
|
||||
write_if_changed(
|
||||
str(run.docs / "emulators" / "index.md"), generate_emulators_index(profiles)
|
||||
@@ -425,7 +426,7 @@ def _write_emulator_page(run: _SiteRun, name: str, profile: dict) -> None:
|
||||
write_single_item(
|
||||
run.public / "api" / "v1" / "emulators" / f"{name}.json", "emulators",
|
||||
{"id": name, "profile": profile},
|
||||
str(db.get("generated_at") or _timestamp()), _source_commit(),
|
||||
str(db.get("generated_at") or data_timestamp()), source_commit(),
|
||||
)
|
||||
pages = emulator_pages(
|
||||
name, profile, db, run.consumers, run.suppl_names, run.data_registry,
|
||||
@@ -461,7 +462,7 @@ def _write_cross_reference(run: _SiteRun) -> None:
|
||||
for stem, page in xref_pages.items():
|
||||
write_if_changed(str(docs / f"{stem}.md"), tables_out_of_search(page))
|
||||
for pname, cov in run.coverages.items():
|
||||
if _own_list_only(cov["config"]):
|
||||
if own_list_only(cov["config"]):
|
||||
# The empty table it had is gone: its address leads to the
|
||||
# platform's page, which says its own list decides alone.
|
||||
sitestarlight.MOVED_PAGES.setdefault(
|
||||
@@ -494,7 +495,7 @@ def _write_gap_pages(run: _SiteRun, provenance_report: dict) -> None:
|
||||
wanted = sitewanted.build_wanted(
|
||||
profiles, coverages, run.gap_report, db, placer, system_name,
|
||||
sitewanted.load_ledger(ledger.ARCHIVES_FILE),
|
||||
_wanted_link(profiles),
|
||||
wanted_link(profiles),
|
||||
)
|
||||
(public / "data").mkdir(parents=True, exist_ok=True)
|
||||
write_if_changed(str(public / sitewanted.DATA_FILE),
|
||||
@@ -542,17 +543,17 @@ def _write_wiki_pages(run: _SiteRun, measured: sitemeasurements.Built) -> None:
|
||||
wiki_src = Path(WIKI_SRC_DIR)
|
||||
# The romset table is the profiles' versions, never typed: the source
|
||||
# page is rewritten before it is copied, as the README is.
|
||||
faq = _REPO_ROOT / ROMSET_FAQ_PAGE
|
||||
faq = REPO_ROOT / ROMSET_FAQ_PAGE
|
||||
if faq.is_file():
|
||||
write_if_changed(str(faq), with_romset_table(faq.read_text(encoding="utf-8"), profiles))
|
||||
recipes_page = _REPO_ROOT / ARCHIVE_RECIPES_PAGE
|
||||
recipes_page = REPO_ROOT / ARCHIVE_RECIPES_PAGE
|
||||
if recipes_page.is_file():
|
||||
write_if_changed(str(recipes_page), with_archive_counts(
|
||||
recipes_page.read_text(encoding="utf-8"), ledger.rebuild_counts()))
|
||||
if wiki_src.is_dir():
|
||||
for src_file in wiki_src.glob("*.md"):
|
||||
shutil.copy2(src_file, wiki_dest / src_file.name)
|
||||
_record(wiki_dest / src_file.name)
|
||||
record_written(wiki_dest / src_file.name)
|
||||
method_page = docs / sitemeasurements.METHOD_PAGE
|
||||
if method_page.is_file():
|
||||
write_if_changed(str(method_page), sitemeasurements.with_hosts(
|
||||
@@ -581,7 +582,7 @@ def _write_guide_pages(run: _SiteRun) -> None:
|
||||
for name in run.platform_names:
|
||||
write_if_changed(str(get_dir / f"{name}.md"), generate_get_page(name))
|
||||
write_if_changed(str(get_dir / f"{GROUP_PAGE}.md"),
|
||||
sitehandheld.group_page(_REPO_ROOT))
|
||||
sitehandheld.group_page(REPO_ROOT))
|
||||
write_if_changed(str(get_dir / "index.md"), generate_get_index())
|
||||
|
||||
print("Generating contributing page...")
|
||||
@@ -596,9 +597,9 @@ def _write_navigation(run: _SiteRun, published_parts: dict[str, str]) -> None:
|
||||
# page no generator produced any more (a console moved back onto its
|
||||
# manufacturer's page) was decorated, recorded, and kept for ever.
|
||||
write_if_changed(str(docs / "404.md"), generate_not_found())
|
||||
stale = _sweep_generated(docs, [d for d in GENERATED_DIRS if d not in PUBLIC_DIRS])
|
||||
stale += _sweep_generated(public, list(PUBLIC_DIRS))
|
||||
stale += _sweep_top_pages(docs)
|
||||
stale = sweep_generated(docs, [d for d in GENERATED_DIRS if d not in PUBLIC_DIRS])
|
||||
stale += sweep_generated(public, list(PUBLIC_DIRS))
|
||||
stale += sweep_top_pages(docs)
|
||||
|
||||
print("Adding page metadata and structured data...")
|
||||
lastmod = decorate_markdown_pages(docs)
|
||||
@@ -616,25 +617,25 @@ def _write_navigation(run: _SiteRun, published_parts: dict[str, str]) -> None:
|
||||
generated = site / "src" / "generated"
|
||||
generated.mkdir(parents=True, exist_ok=True)
|
||||
write_if_changed(str(generated / "sidebar.json"),
|
||||
json.dumps(sitestarlight.sidebar(nav, present, _overview_anchors(nav, docs)),
|
||||
json.dumps(sitestarlight.sidebar(nav, present, overview_anchors(nav, docs)),
|
||||
indent=1) + "\n")
|
||||
write_if_changed(str(generated / "redirects.json"),
|
||||
json.dumps(sitestarlight.redirects(run.profiles, present, published_parts), indent=1,
|
||||
sort_keys=True) + "\n")
|
||||
write_if_changed(str(generated / "lastmod.json"),
|
||||
json.dumps(dict(sorted(lastmod.items())), indent=1) + "\n")
|
||||
system_ids = set(_system_page_map) | {
|
||||
system_ids = set(system_page_map) | {
|
||||
sys_id for cov in coverages.values() for sys_id in cov["config"].get("systems", {})
|
||||
}
|
||||
titles = {sys_id: system_name(sys_id) for sys_id in sorted(system_ids)}
|
||||
sitestarlight.picker_data(_REPO_ROOT / "install", public / "data" / "picker", titles)
|
||||
sitestarlight.picker_data(REPO_ROOT / "install", public / "data" / "picker", titles)
|
||||
total_pages = len(present)
|
||||
print(f"\nGenerated {total_pages} pages in {run.args.docs_dir}/")
|
||||
if stale:
|
||||
print(f"Removed {stale} page(s) nothing produced this run")
|
||||
|
||||
|
||||
def _generate(args: argparse.Namespace) -> None:
|
||||
def generate_site(args: argparse.Namespace) -> None:
|
||||
|
||||
# Every page reads these, never the repository's own files.
|
||||
siteinputs.use(siteinputs.SiteInputs(
|
||||
@@ -659,24 +660,24 @@ def _generate(args: argparse.Namespace) -> None:
|
||||
|
||||
# The test each emulator page builds for itself: the parts a page is
|
||||
# cut into weigh the status its rows show.
|
||||
run.file_held = _availability_check(db, run.suppl_names)
|
||||
run.file_held = availability_check(db, run.suppl_names)
|
||||
# The plan names systems: the sections must be this run's data first.
|
||||
run.manufacturers = _group_by_manufacturer(db)
|
||||
run.manufacturers = group_by_manufacturer(db)
|
||||
set_console_sections(run.manufacturers, program_names(profiles))
|
||||
plan_emulator_pages(profiles, run.file_held)
|
||||
# Build system_id -> manufacturer page map (needed by all generators)
|
||||
print("Building system cross-reference map...")
|
||||
set_system_page_map(
|
||||
_system_pages_from_data(run.manufacturers, coverages, db, profiles)
|
||||
system_pages_from_data(run.manufacturers, coverages, db, profiles)
|
||||
)
|
||||
print(f" {len(_system_page_map)} system IDs mapped to pages")
|
||||
print(f" {len(system_page_map)} system IDs mapped to pages")
|
||||
_write_system_pages(run)
|
||||
|
||||
measured = _write_measurements(run)
|
||||
_write_data_exports(run, stats)
|
||||
|
||||
export_reports = load_export_reports()
|
||||
_EXPORTED.update(report["platform"] for report in export_reports)
|
||||
EXPORTED.update(report["platform"] for report in export_reports)
|
||||
|
||||
published_parts = _write_platform_pages(run)
|
||||
_write_emulator_pages(run)
|
||||
|
||||
+49
-48
@@ -11,13 +11,14 @@ import urllib.parse
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
|
||||
from model.collection import _profiles_on_disk
|
||||
from model.collection import profiles_on_disk
|
||||
from packs.crossref import FileConsumers
|
||||
from sitegen import markup, wanted as sitewanted
|
||||
from sitegen.config import REPO_URL, _REPO_ROOT
|
||||
from sitegen.config import REPO_URL
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.fields import search_excluded
|
||||
from sitegen.install import _platform_display
|
||||
from sitegen.render import _code, _count, _system_page_map, emulator_card_page
|
||||
from sitegen.install import platform_display
|
||||
from sitegen.render import code_span, count_text, system_page_map, emulator_card_page
|
||||
|
||||
|
||||
def emulator_file_anchors(files: list[dict]) -> list[str]:
|
||||
@@ -67,7 +68,7 @@ def emulator_file_anchors(files: list[dict]) -> list[str]:
|
||||
return anchors
|
||||
|
||||
|
||||
_PROVENANCE_LABELS = {"redump": "Redump", "no-intro": "No-Intro", "tosec": "TOSEC"}
|
||||
PROVENANCE_LABELS = {"redump": "Redump", "no-intro": "No-Intro", "tosec": "TOSEC"}
|
||||
|
||||
|
||||
# TOSEC dump flags that say the dump is not a clean copy of the chip
|
||||
@@ -102,19 +103,19 @@ def _provenance_lines(provenance: dict, prefix: str) -> list[str]:
|
||||
"""
|
||||
lines: list[str] = []
|
||||
for source, data in sorted(provenance.items()):
|
||||
label = _PROVENANCE_LABELS.get(source, source)
|
||||
label = PROVENANCE_LABELS.get(source, source)
|
||||
flags = _dump_flags(source, data)
|
||||
kind = "rb-badge-warning" if flags else "rb-badge-success"
|
||||
badge = f'<span class="rb-badge {kind}">[{label}]({prefix}provenance.md#{source})</span>'
|
||||
name = str(data.get("name") or data.get("description") or "")
|
||||
line = f"- Catalogued: {badge} {_code(name)}" if name else f"- Catalogued: {badge}"
|
||||
line = f"- Catalogued: {badge} {code_span(name)}" if name else f"- Catalogued: {badge}"
|
||||
if flags:
|
||||
line += f" ({', '.join(flags)}, as {label} records it)"
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
_ROMSET_SOURCES = {"mame": "MAME", "fbneo": "FBNeo"}
|
||||
ROMSET_SOURCES = {"mame": "MAME", "fbneo": "FBNeo"}
|
||||
|
||||
|
||||
_RELEASE_ASSET_NAMES: dict[str, str] | None = None
|
||||
@@ -124,10 +125,10 @@ def _download_name(path: str) -> str:
|
||||
"""The name a browser saves a collection file under: the last segment
|
||||
of its download URL. Neither host sends a Content-Disposition, and the
|
||||
download attribute is ignored on another origin."""
|
||||
return urllib.parse.unquote(_fetch_url(path).rsplit("/", 1)[-1])
|
||||
return urllib.parse.unquote(fetch_url(path).rsplit("/", 1)[-1])
|
||||
|
||||
|
||||
def _fetch_url(path: str) -> str:
|
||||
def fetch_url(path: str) -> str:
|
||||
"""Where a collection file downloads from: its raw URL, or the
|
||||
large-files release asset when .gitignore keeps it out of git."""
|
||||
global _RELEASE_ASSET_NAMES
|
||||
@@ -154,7 +155,7 @@ def _fetch_url(path: str) -> str:
|
||||
Place = tuple[str, str, list[str]]
|
||||
|
||||
|
||||
def _platform_places(sha1: str, consumers: FileConsumers) -> list[Place]:
|
||||
def platform_places(sha1: str, consumers: FileConsumers) -> list[Place]:
|
||||
"""Each platform declaring the file, linked to its system section, with
|
||||
the destination it gives the file."""
|
||||
systems_of = getattr(consumers, "platform_systems", {}).get(sha1, {})
|
||||
@@ -163,24 +164,24 @@ def _platform_places(sha1: str, consumers: FileConsumers) -> list[Place]:
|
||||
for platform in consumers.platforms.get(sha1, ()):
|
||||
section = sorted(systems_of.get(platform, ()))
|
||||
fragment = f"#{section[0].replace(' ', '-')}" if section else ""
|
||||
places.append((_platform_display(platform), f"../platforms/{platform}.md{fragment}",
|
||||
places.append((platform_display(platform), f"../platforms/{platform}.md{fragment}",
|
||||
sorted(destinations_of.get(platform, ()))))
|
||||
return sorted(places, key=lambda place: place[0].casefold())
|
||||
|
||||
|
||||
def _platform_links(sha1: str, consumers: FileConsumers) -> list[str]:
|
||||
def platform_links(sha1: str, consumers: FileConsumers) -> list[str]:
|
||||
"""Each platform declaring the file, as Markdown: its name, linked to
|
||||
its system section, then the destination it gives the file."""
|
||||
return [
|
||||
f"[{name}]({href})" + (": " + ", ".join(_code(d) for d in dests) if dests else "")
|
||||
for name, href, dests in _platform_places(sha1, consumers)
|
||||
f"[{name}]({href})" + (": " + ", ".join(code_span(d) for d in dests) if dests else "")
|
||||
for name, href, dests in platform_places(sha1, consumers)
|
||||
]
|
||||
|
||||
|
||||
_card_anchors: dict[str, tuple[list, list[str]]] = {}
|
||||
|
||||
|
||||
def _emulator_card_anchor(emulator: str, files: list, index: int) -> str:
|
||||
def emulator_card_anchor(emulator: str, files: list, index: int) -> str:
|
||||
"""The id of a profile entry's card on its emulator page."""
|
||||
cached = _card_anchors.get(emulator)
|
||||
if cached is None or cached[0] is not files:
|
||||
@@ -188,13 +189,13 @@ def _emulator_card_anchor(emulator: str, files: list, index: int) -> str:
|
||||
return cached[1][index] if 0 <= index < len(cached[1]) else ""
|
||||
|
||||
|
||||
def _wanted_link(profiles: dict) -> Callable[[str, str, dict], str]:
|
||||
def wanted_link(profiles: dict) -> Callable[[str, str, dict], str]:
|
||||
"""The page a row of the wanted list links: an emulator entry's card,
|
||||
where its notes, hashes and source line are, else the setup's page."""
|
||||
def link(kind: str, key: str, entry: dict) -> str:
|
||||
files = (profiles.get(key) or {}).get("files") or [] if kind == "emulator" else []
|
||||
index = next((i for i, f in enumerate(files) if f is entry), -1)
|
||||
anchor = _emulator_card_anchor(key, files, index) if index >= 0 else ""
|
||||
anchor = emulator_card_anchor(key, files, index) if index >= 0 else ""
|
||||
if anchor:
|
||||
return f"emulators/{emulator_card_page(key, anchor)}/#{anchor}"
|
||||
return sitewanted.reader_page(kind, key, entry)
|
||||
@@ -213,11 +214,11 @@ def _emulator_links(sha1: str, consumers: FileConsumers) -> list[str]:
|
||||
links = []
|
||||
# By the name the emulator's page carries: 19,499 card links read
|
||||
# melonds_ds where its page says melonDS DS.
|
||||
named = sorted(((_emulator_display(e), e) for e in consumers.emulators.get(sha1, ())),
|
||||
named = sorted(((emulator_display(e), e) for e in consumers.emulators.get(sha1, ())),
|
||||
key=lambda pair: (pair[0].casefold(), pair[1]))
|
||||
for display, emulator in named:
|
||||
index = entries.get(emulator)
|
||||
anchor = (_emulator_card_anchor(emulator, files_of[emulator], index)
|
||||
anchor = (emulator_card_anchor(emulator, files_of[emulator], index)
|
||||
if index is not None and emulator in files_of else "")
|
||||
page = emulator_card_page(emulator, anchor) if anchor else emulator
|
||||
fragment = f"#{anchor}" if anchor else ""
|
||||
@@ -232,7 +233,7 @@ def _installed_places(sha1: str, consumers: FileConsumers, declared: set[str]) -
|
||||
"""Each pack installing the file that its platform's list does not name,
|
||||
with the place the pack gives it."""
|
||||
places = [
|
||||
(_platform_display(platform), f"../platforms/{platform}.md", sorted(d for d in dests if d))
|
||||
(platform_display(platform), f"../platforms/{platform}.md", sorted(d for d in dests if d))
|
||||
for platform, dests in getattr(consumers, "installed", {}).get(sha1, {}).items()
|
||||
if platform not in declared
|
||||
]
|
||||
@@ -258,14 +259,14 @@ def _places_lines(places: list[Place]) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def _places_markdown(places: list[Place]) -> list[str]:
|
||||
def places_markdown(places: list[Place]) -> list[str]:
|
||||
"""_places_lines in Markdown, for a card written as a list: the places
|
||||
as code spans, which the glossary and the line breaks treat as code."""
|
||||
by_place: dict[tuple[str, ...], list[str]] = {}
|
||||
for name, href, dests in places:
|
||||
by_place.setdefault(tuple(dests), []).append(f"[{name}]({href})")
|
||||
ordered = sorted(by_place.items(), key=lambda item: (not item[0], -len(item[1]), item[0]))
|
||||
return [(" and ".join(_code(d) for d in dests) + ": " if dests else "") + ", ".join(links)
|
||||
return [(" and ".join(code_span(d) for d in dests) + ": " if dests else "") + ", ".join(links)
|
||||
for dests, links in ordered]
|
||||
|
||||
|
||||
@@ -296,7 +297,7 @@ _PERMALINK_ICON = ('<svg aria-hidden="true" width="16" height="16">'
|
||||
'<use href="#rb-link-icon"/></svg>')
|
||||
|
||||
|
||||
def _icon_symbol() -> list[str]:
|
||||
def icon_symbol() -> list[str]:
|
||||
"""The icon's drawing, for a page of cards. None in the yardstick."""
|
||||
return [PERMALINK_SYMBOL, ""] if markup.starlight() else []
|
||||
|
||||
@@ -316,12 +317,12 @@ def _release_name(source: str, label: str, versions: dict) -> str:
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def _romset_snapshots() -> list[tuple[str, dict]]:
|
||||
return [(str(snapshot.get("source", path.stem)), snapshot)
|
||||
for path in sorted((_REPO_ROOT / "recipes").glob("*.json"))
|
||||
for path in sorted((REPO_ROOT / "recipes").glob("*.json"))
|
||||
for snapshot in [json.loads(path.read_text(encoding="utf-8"))]]
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def _romset_releases() -> dict[str, list[tuple[RomsetMembers, str, list[Release]]]]:
|
||||
def romset_releases() -> dict[str, list[tuple[RomsetMembers, str, list[Release]]]]:
|
||||
"""Archive name -> (members, source, the releases agreeing on them), from
|
||||
the MAME and FBNeo recipe snapshots under recipes/.
|
||||
|
||||
@@ -374,8 +375,8 @@ def _romset_line(f: dict) -> str:
|
||||
match" when names had to agree and no member could be extra. Empty
|
||||
when no recipe names the archive or the file is not on disk.
|
||||
"""
|
||||
recipes = _romset_releases().get(str(f.get("name", "")))
|
||||
path = _REPO_ROOT / str(f.get("path", ""))
|
||||
recipes = romset_releases().get(str(f.get("name", "")))
|
||||
path = REPO_ROOT / str(f.get("path", ""))
|
||||
if not recipes or not path.is_file():
|
||||
return ""
|
||||
try:
|
||||
@@ -404,7 +405,7 @@ def _romset_line(f: dict) -> str:
|
||||
|
||||
def runs(found: dict[str, list[Release]], skip: dict[str, list[Release]]) -> str:
|
||||
return " and ".join(
|
||||
f"{_ROMSET_SOURCES.get(source, source)} {_release_runs(kept)}"
|
||||
f"{ROMSET_SOURCES.get(source, source)} {_release_runs(kept)}"
|
||||
for source in sorted(found, key=_source_order)
|
||||
for kept in [[r for r in found[source] if r not in skip.get(source, [])]] if kept)
|
||||
|
||||
@@ -418,7 +419,7 @@ def _romset_line(f: dict) -> str:
|
||||
if not closest:
|
||||
return f"No match in {_romset_coverage()}"
|
||||
return "No match: missing " + ", ".join(
|
||||
f"{_count(missing, 'ROM')} of {_ROMSET_SOURCES.get(source, source)} {release[1]}"
|
||||
f"{count_text(missing, 'ROM')} of {ROMSET_SOURCES.get(source, source)} {release[1]}"
|
||||
for source, (missing, release) in sorted(closest.items(),
|
||||
key=lambda item: _source_order(item[0])))
|
||||
|
||||
@@ -434,14 +435,14 @@ def _romset_coverage() -> str:
|
||||
for index, label in enumerate(versions)]
|
||||
# The ends of the span, read as one run.
|
||||
span = [ends[0], (1, ends[-1][1])] if len(ends) > 1 else ends
|
||||
covered[source] = f"{_ROMSET_SOURCES.get(source, source)} {_release_runs(span)}"
|
||||
covered[source] = f"{ROMSET_SOURCES.get(source, source)} {_release_runs(span)}"
|
||||
return " or ".join(covered[source] for source in sorted(covered, key=_source_order))
|
||||
|
||||
|
||||
ROMSET_FAQ = "../wiki/technical-faq.md#which-mame-version-do-the-arcade-bios-sets-match"
|
||||
|
||||
|
||||
def _system_file_card(
|
||||
def system_file_card(
|
||||
f: dict, consumers: FileConsumers, anchored: set[str] | None = None,
|
||||
searchable: bool = True,
|
||||
) -> list[str]:
|
||||
@@ -487,11 +488,11 @@ def _system_file_card(
|
||||
# The download leads the card: as a "(download)" after the collection
|
||||
# path, fourth of the facts, a reader of the Apple II page found none.
|
||||
download = (
|
||||
f' <a class="rb-download" href="{html.escape(_fetch_url(f["path"]))}" '
|
||||
f' <a class="rb-download" href="{html.escape(fetch_url(f["path"]))}" '
|
||||
f'aria-label="Download {html.escape(name)}" {skip}>Download</a>'
|
||||
) if f.get("path") and markup.starlight() else ""
|
||||
lines.append(_card_title(
|
||||
f'{_code(name)} <span class="rb-badge rb-badge-muted">{size}</span>{unread}{download}{permalink}',
|
||||
lines.append(card_title(
|
||||
f'{code_span(name)} <span class="rb-badge rb-badge-muted">{size}</span>{unread}{download}{permalink}',
|
||||
anchor, searchable,
|
||||
))
|
||||
lines.append("")
|
||||
@@ -504,14 +505,14 @@ def _system_file_card(
|
||||
# A .variants/ copy is stored as advision.zip.1c086064, and the
|
||||
# browser names the download after the URL: copied as it came, the
|
||||
# file a platform pins was not found under its name.
|
||||
facts.append(("Save as", [f"{_code(name)}, the download is named {_code(saved)}"], False))
|
||||
facts.append(("Save as", [f"{code_span(name)}, the download is named {code_span(saved)}"], False))
|
||||
if plats:
|
||||
# Each link lands on the platform's system section, and says where
|
||||
# that platform puts the file. Out of the search: the card's title
|
||||
# weighs the most a word can, and the list made the excerpt of
|
||||
# every card a run of setup names and paths.
|
||||
facts.append(("On the setup's list",
|
||||
_places_lines(_platform_places(sha1_full, consumers)), False))
|
||||
_places_lines(platform_places(sha1_full, consumers)), False))
|
||||
if installed:
|
||||
# The packs that carry the file for their cores: a RetroBat user
|
||||
# looking up scph5501.bin found every platform but RetroBat, whose
|
||||
@@ -528,9 +529,9 @@ def _system_file_card(
|
||||
# The card named a file, its hashes and provenance, but not where to
|
||||
# get it: a user missing scph5501.bin found the reference and no way
|
||||
# to the bytes.
|
||||
path = _code(f["path"])
|
||||
path = code_span(f["path"])
|
||||
if not markup.starlight():
|
||||
path += f" ([download]({_fetch_url(f['path'])}))"
|
||||
path += f" ([download]({fetch_url(f['path'])}))"
|
||||
facts.append(("Collection path", [path], False))
|
||||
catalogued = [line.split(": ", 1)[1]
|
||||
for line in _provenance_lines(f.get("provenance") or {}, "../")]
|
||||
@@ -573,7 +574,7 @@ _CARD_MORE_WORDS = {"Romset": "romset", "Collection path": "collection path",
|
||||
SHORT_HASH = 12
|
||||
|
||||
|
||||
def _listed_words(words: list[str]) -> str:
|
||||
def listed_words(words: list[str]) -> str:
|
||||
""""a", "a and b", "a, b and c", first letter capital."""
|
||||
text = words[0] if len(words) == 1 else f"{', '.join(words[:-1])} and {words[-1]}"
|
||||
return text[:1].upper() + text[1:]
|
||||
@@ -654,7 +655,7 @@ def _card_fact_groups(facts: list[tuple[str, list[str], bool]], sha1: str,
|
||||
_CARD_MORE_WORDS.get(label, label.lower()) for label, _values, _searched in more]
|
||||
# On one line: nothing reads it as Markdown, and a page cut by size
|
||||
# holds its cards in the same bytes.
|
||||
lines += card_fold(_listed_words(words),
|
||||
lines += card_fold(listed_words(words),
|
||||
["".join(_fact_list(folded, "", dict.fromkeys(_CARD_HASHES, "rb-hash")))])
|
||||
return lines
|
||||
|
||||
@@ -707,7 +708,7 @@ SEARCH_SKIPPED = (
|
||||
)
|
||||
|
||||
|
||||
def _search_skipped_apart(lines: list[str]) -> list[str]:
|
||||
def search_skipped_apart(lines: list[str]) -> list[str]:
|
||||
"""Card list lines, each run the search skips in a block of its own."""
|
||||
out: list[str] = []
|
||||
skipping = False
|
||||
@@ -725,7 +726,7 @@ def _search_skipped_apart(lines: list[str]) -> list[str]:
|
||||
return out
|
||||
|
||||
|
||||
def _card_title(text: str, anchor: str, searchable: bool = True, weight: int = 10) -> str:
|
||||
def card_title(text: str, anchor: str, searchable: bool = True, weight: int = 10) -> str:
|
||||
"""A file card's heading, so the site search lands on the card.
|
||||
|
||||
The search splits a page at its headings: a card titled in bold sent a
|
||||
@@ -760,11 +761,11 @@ def system_install_choices(coverages: dict) -> dict[str, dict[str, list[tuple[st
|
||||
platform's install manifest records is offered: --system refuses any
|
||||
other name.
|
||||
"""
|
||||
from sitegen.render import _page_by_norm
|
||||
from sitegen.render import page_by_norm
|
||||
|
||||
choices: dict[str, dict[str, list[tuple[str, str]]]] = {}
|
||||
for name, cov in sorted(coverages.items()):
|
||||
manifest = _REPO_ROOT / "install" / f"{name}.json"
|
||||
manifest = REPO_ROOT / "install" / f"{name}.json"
|
||||
if not manifest.is_file():
|
||||
continue
|
||||
document = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
@@ -774,15 +775,15 @@ def system_install_choices(coverages: dict) -> dict[str, dict[str, list[tuple[st
|
||||
for system in entry.get("systems") or []
|
||||
}
|
||||
for sys_id in sorted(set(cov["config"].get("systems") or {}) & recorded):
|
||||
page = _system_page_map.get(sys_id) or _page_by_norm(sys_id)
|
||||
page = system_page_map.get(sys_id) or page_by_norm(sys_id)
|
||||
if page:
|
||||
slug, console = page
|
||||
choices.setdefault(slug, {}).setdefault(console, []).append((name, sys_id))
|
||||
return choices
|
||||
|
||||
|
||||
def _emulator_display(emulator: str) -> str:
|
||||
return str((_profiles_on_disk().get(emulator) or {}).get("emulator") or emulator)
|
||||
def emulator_display(emulator: str) -> str:
|
||||
return str((profiles_on_disk().get(emulator) or {}).get("emulator") or emulator)
|
||||
|
||||
|
||||
def _first_hash_value(entry: dict) -> str:
|
||||
|
||||
@@ -5,7 +5,6 @@ from __future__ import annotations
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from model import releaserecord
|
||||
from core.paths import REPO_ROOT
|
||||
from model.safeparse import require_yaml
|
||||
|
||||
|
||||
@@ -27,7 +26,7 @@ GENERATED_DIRS = ["platforms", "systems", "emulators", "wiki", "api", "downloads
|
||||
PUBLIC_DIRS = ("api", "downloads")
|
||||
|
||||
|
||||
def _timestamp() -> str:
|
||||
def data_timestamp() -> str:
|
||||
"""The build time for data files (stats, API records), ISO 8601."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
@@ -40,12 +39,9 @@ def data_as_of(moment: datetime | None = None) -> str:
|
||||
f"Data as of {moment.day} {moment.strftime('%B %Y')}</time>")
|
||||
|
||||
|
||||
def _date_line() -> str:
|
||||
def date_line() -> str:
|
||||
"""The date a page closes on, in the words of data_as_of(). The search
|
||||
does not read it: a query word such as the "2" of "playstation 2 bios"
|
||||
also matches the start of "2026", and every page closing on the date
|
||||
then held every word of the query."""
|
||||
return f'<div class="rb-timestamp" data-pagefind-ignore>{data_as_of()}.</div>'
|
||||
|
||||
|
||||
_REPO_ROOT = REPO_ROOT
|
||||
@@ -5,12 +5,12 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import TypeVar
|
||||
|
||||
from model.collection import _profiles_on_disk
|
||||
from model.collection import profiles_on_disk
|
||||
from model.composition import GAME_DATA_TOPS
|
||||
from model.guides import INSTALL_PS1, INSTALL_SH
|
||||
from model.profiles import entry_system_ids
|
||||
from packs.crossref import FileConsumers
|
||||
from sitegen.cards import _emulator_display, _romset_releases, _system_file_card
|
||||
from sitegen.cards import emulator_display, romset_releases, system_file_card
|
||||
|
||||
|
||||
# A manufacturer page above this much Markdown becomes a summary with one
|
||||
@@ -41,7 +41,7 @@ SYSTEM_SUMMARY_HTML = 500_000
|
||||
FITTED_ADDRESS_CHARS = {INSTALL_PS1: 67, INSTALL_SH: 66}
|
||||
|
||||
|
||||
def _install_box_weight(lines: list[str]) -> int:
|
||||
def install_box_weight(lines: list[str]) -> int:
|
||||
weight = 0
|
||||
for line in lines:
|
||||
weight += len(line) + 1
|
||||
@@ -54,7 +54,7 @@ def _install_box_weight(lines: list[str]) -> int:
|
||||
|
||||
# A system card: whether it is a variant, its lines, its sha1.
|
||||
Card = tuple[bool, list[str], str]
|
||||
_Item = TypeVar("_Item")
|
||||
Item = TypeVar("Item")
|
||||
|
||||
|
||||
def _reading_entries(sha1: str, consumers: FileConsumers) -> list[dict]:
|
||||
@@ -68,10 +68,10 @@ def _reading_entries(sha1: str, consumers: FileConsumers) -> list[dict]:
|
||||
return entries
|
||||
|
||||
|
||||
_NO_PRIORITY = 1 << 30
|
||||
NO_PRIORITY = 1 << 30
|
||||
|
||||
|
||||
def _card_rank(f: dict, consumers: FileConsumers, start: dict[str, int] | None = None) -> tuple:
|
||||
def card_rank(f: dict, consumers: FileConsumers, start: dict[str, int] | None = None) -> tuple:
|
||||
"""Where a file's card sits in its console: the files the section's
|
||||
start line names first, in its order (``start``, sha1 -> place), then
|
||||
the files an emulator requires, then by the emulators' search order
|
||||
@@ -89,9 +89,9 @@ def _card_rank(f: dict, consumers: FileConsumers, start: dict[str, int] | None =
|
||||
priorities = [e["priority"] for e in entries if isinstance(e.get("priority"), int)]
|
||||
required = any(e.get("required", True) for e in entries)
|
||||
return (
|
||||
(start or {}).get(sha1, _NO_PRIORITY),
|
||||
(start or {}).get(sha1, NO_PRIORITY),
|
||||
not required,
|
||||
min(priorities, default=_NO_PRIORITY),
|
||||
min(priorities, default=NO_PRIORITY),
|
||||
-len(entries) if required else 0,
|
||||
-len(consumers.platforms.get(sha1, ())),
|
||||
f["name"].casefold(), f["name"], f.get("path", ""),
|
||||
@@ -102,7 +102,7 @@ def _by_name(f: dict) -> tuple:
|
||||
return f["name"].casefold(), f["name"], f.get("path", "")
|
||||
|
||||
|
||||
def _console_cards(
|
||||
def console_cards(
|
||||
manufacturer: str,
|
||||
files: list[dict],
|
||||
consumers: FileConsumers,
|
||||
@@ -120,13 +120,13 @@ def _console_cards(
|
||||
|
||||
def order(f: dict) -> tuple:
|
||||
if by_name:
|
||||
return (place.get(str(f.get("sha1", "")), _NO_PRIORITY), *_by_name(f))
|
||||
return _card_rank(f, consumers, place)
|
||||
return (place.get(str(f.get("sha1", "")), NO_PRIORITY), *_by_name(f))
|
||||
return card_rank(f, consumers, place)
|
||||
# Another revision of a MAME or FBNeo set is another release's set, its
|
||||
# Romset line saying which: it sits open beside the set of its name.
|
||||
# Twelve neogeo.zip were on five pages, the SNK ones closed under
|
||||
# Variants.
|
||||
romsets = _romset_releases()
|
||||
romsets = romset_releases()
|
||||
beside = [f for f in files if "/.variants/" in f["path"] and f["name"] in romsets]
|
||||
main_files = [f for f in files if "/.variants/" not in f["path"]]
|
||||
variant_files = [f for f in files if "/.variants/" in f["path"] and f not in beside]
|
||||
@@ -143,9 +143,9 @@ def _console_cards(
|
||||
elif by_set.get(f["name"]):
|
||||
ordered.extend(by_set.pop(f["name"]))
|
||||
ordered.extend(f for files in by_set.values() for f in files)
|
||||
cards = [(False, _system_file_card(f, consumers, anchored, searchable), str(f.get("sha1", "")))
|
||||
cards = [(False, system_file_card(f, consumers, anchored, searchable), str(f.get("sha1", "")))
|
||||
for f in ordered]
|
||||
cards += [(True, _system_file_card(v, consumers, anchored, searchable), str(v.get("sha1", "")))
|
||||
cards += [(True, system_file_card(v, consumers, anchored, searchable), str(v.get("sha1", "")))
|
||||
for v in sorted(variant_files, key=order)]
|
||||
return cards
|
||||
|
||||
@@ -155,7 +155,7 @@ def _console_cards(
|
||||
START_WITH_NAMES = 6
|
||||
|
||||
|
||||
def _region_order() -> dict[str, int]:
|
||||
def region_order() -> dict[str, int]:
|
||||
"""The regions a start line lists, the territories first. A file read
|
||||
for every region is a region-free stand-in for the BIOS of each one:
|
||||
the PlayStation section opened on psxonpsp660.bin, which one emulator
|
||||
@@ -169,7 +169,7 @@ def _region_order() -> dict[str, int]:
|
||||
return {region: index for index, region in enumerate(ordered)}
|
||||
|
||||
|
||||
def _reading_pairs(sha1: str, consumers: FileConsumers) -> list[tuple[str, dict]]:
|
||||
def reading_pairs(sha1: str, consumers: FileConsumers) -> list[tuple[str, dict]]:
|
||||
"""The profile entries that read a file, each with its emulator."""
|
||||
files_of = getattr(consumers, "emulator_files", {})
|
||||
pairs = []
|
||||
@@ -180,12 +180,12 @@ def _reading_pairs(sha1: str, consumers: FileConsumers) -> list[tuple[str, dict]
|
||||
return pairs
|
||||
|
||||
|
||||
def _entry_systems(emulator: str, entry: dict) -> list[str]:
|
||||
def entry_systems(emulator: str, entry: dict) -> list[str]:
|
||||
"""The systems an entry is read for: its own `system:` or `systems:`
|
||||
(a MAME device set several systems load), else its profile's only one."""
|
||||
if entry.get("system") or entry.get("systems"):
|
||||
return entry_system_ids(entry, {})
|
||||
systems = (_profiles_on_disk().get(emulator) or {}).get("systems") or []
|
||||
systems = (profiles_on_disk().get(emulator) or {}).get("systems") or []
|
||||
return [str(systems[0])] if len(systems) == 1 else []
|
||||
|
||||
|
||||
@@ -193,7 +193,7 @@ def _entry_systems(emulator: str, entry: dict) -> list[str]:
|
||||
_SECTION_ENTRIES: dict[int, tuple[object, dict[tuple[str, str], list]]] = {}
|
||||
|
||||
|
||||
def _entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]:
|
||||
def entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]:
|
||||
"""Each console section with the (sha1, emulator, entry, system) whose
|
||||
system leads to it, read once per build."""
|
||||
from sitegen.render import system_section
|
||||
@@ -204,8 +204,8 @@ def _entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]
|
||||
sections: dict[str, tuple[str, str] | None] = {}
|
||||
index: dict[tuple[str, str], list] = {}
|
||||
for sha1 in sorted(getattr(consumers, "emulator_entries", {})):
|
||||
for emulator, entry in _reading_pairs(sha1, consumers):
|
||||
for sys_id in _entry_systems(emulator, entry):
|
||||
for emulator, entry in reading_pairs(sha1, consumers):
|
||||
for sys_id in entry_systems(emulator, entry):
|
||||
if sys_id not in sections:
|
||||
sections[sys_id] = system_section(sys_id)
|
||||
place = sections[sys_id]
|
||||
@@ -216,7 +216,7 @@ def _entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]
|
||||
return index
|
||||
|
||||
|
||||
def _setup_name(f: dict, consumers: FileConsumers, pairs: list[tuple[str, dict]]) -> str:
|
||||
def setup_name(f: dict, consumers: FileConsumers, pairs: list[tuple[str, dict]]) -> str:
|
||||
"""The name most setups give a file, else most emulators: the collection
|
||||
keeps BizHawk's GBA_bios.rom where eight setups write gba_bios.bin."""
|
||||
counts: dict[str, int] = {}
|
||||
@@ -236,22 +236,22 @@ def _setup_name(f: dict, consumers: FileConsumers, pairs: list[tuple[str, dict]]
|
||||
return f["name"] if f["name"] in top else top[0]
|
||||
|
||||
|
||||
def _without_files(emulators: list[str]) -> str:
|
||||
def without_files(emulators: list[str]) -> str:
|
||||
"""Who runs without the files: every emulator reading one, up to three
|
||||
by name, more counted, as their order would rank nothing."""
|
||||
names = sorted({_emulator_display(e) for e in emulators}, key=str.casefold)
|
||||
names = sorted({emulator_display(e) for e in emulators}, key=str.casefold)
|
||||
if len(names) > 3:
|
||||
return f": none of its {len(names)} emulators requires one"
|
||||
return " with " + (", ".join(names[:-1]) + f" or {names[-1]}" if len(names) > 1 else names[0])
|
||||
|
||||
|
||||
def _visible(name: str) -> str:
|
||||
def visible_name(name: str) -> str:
|
||||
"""The file name a start line shows, out of its code span and link."""
|
||||
match = re.match(r"\[?`([^`]*)`", name)
|
||||
return match[1] if match else name
|
||||
|
||||
|
||||
def _add_name(names: list[str], name: str) -> None:
|
||||
def add_name(names: list[str], name: str) -> None:
|
||||
"""A name once per line: two copies of sfcbox.zip read as one file."""
|
||||
if all(_visible(n) != _visible(name) for n in names):
|
||||
if all(visible_name(n) != visible_name(name) for n in names):
|
||||
names.append(name)
|
||||
+18
-18
@@ -8,11 +8,11 @@ import urllib.parse
|
||||
from model.systemnames import system_name
|
||||
from resolve.cores import resolve_platform_cores
|
||||
from sitegen import markup
|
||||
from sitegen.config import _date_line
|
||||
from sitegen.config import date_line
|
||||
from sitegen.emulatorsindex import CLS_LABEL_ONE
|
||||
from sitegen.parts import _parent_front_matter
|
||||
from sitegen.platformpage import OWN_LIST_ONLY, _own_list_only
|
||||
from sitegen.render import _count, _escape_tags
|
||||
from sitegen.parts import parent_front_matter
|
||||
from sitegen.platformpage import OWN_LIST_ONLY, own_list_only
|
||||
from sitegen.render import count_text, escape_tags
|
||||
|
||||
|
||||
def _core_scope_note(config: dict, profiles: dict) -> str:
|
||||
@@ -30,10 +30,10 @@ def _core_scope_note(config: dict, profiles: dict) -> str:
|
||||
others = len(resolved - every_libretro)
|
||||
if not others:
|
||||
return " (all libretro)"
|
||||
return f" (all libretro, plus {_count(others, 'other core')})"
|
||||
return f" (all libretro, plus {count_text(others, 'other core')})"
|
||||
|
||||
|
||||
def _gap_sources(data: dict) -> dict[str, int]:
|
||||
def gap_sources(data: dict) -> dict[str, int]:
|
||||
"""Where each undeclared file of one emulator comes from.
|
||||
|
||||
A file the emulator's own package installs is not one to find. The
|
||||
@@ -106,7 +106,7 @@ def _upstream_label(key: str) -> str:
|
||||
def _breakable(label: str) -> str:
|
||||
"""A project address that may wrap after each slash: unbroken, the
|
||||
longest pushed three of five columns off a 1,440 px screen."""
|
||||
return "/<wbr>".join(_escape_tags(part) for part in label.split("/"))
|
||||
return "/<wbr>".join(escape_tags(part) for part in label.split("/"))
|
||||
|
||||
|
||||
def _xref_platform_rows(config: dict, unique: dict) -> tuple[int, list[str]]:
|
||||
@@ -120,7 +120,7 @@ def _xref_platform_rows(config: dict, unique: dict) -> tuple[int, list[str]]:
|
||||
p = unique[emu_name]
|
||||
cls_raw = p.get("core_classification", "-")
|
||||
systems = p.get("systems", []) or []
|
||||
sys_str = ", ".join(_escape_tags(system_name(s)) for s in systems[:3])
|
||||
sys_str = ", ".join(escape_tags(system_name(s)) for s in systems[:3])
|
||||
if len(systems) > 3:
|
||||
sys_str += f" +{len(systems) - 3}"
|
||||
files = p.get("files", []) or []
|
||||
@@ -134,9 +134,9 @@ def _xref_platform_rows(config: dict, unique: dict) -> tuple[int, list[str]]:
|
||||
upstream = _xref_upstream(p)
|
||||
key, _rest = upstream_project(upstream)
|
||||
upstream_display = (f"[{_breakable(_upstream_label(key))}]({upstream.split()[0]})"
|
||||
if upstream.startswith("http") else (_escape_tags(upstream) or "-"))
|
||||
if upstream.startswith("http") else (escape_tags(upstream) or "-"))
|
||||
rows.append(
|
||||
f"| [{_escape_tags(p.get('emulator', emu_name))}](emulators/{emu_name}.md) "
|
||||
f"| [{escape_tags(p.get('emulator', emu_name))}](emulators/{emu_name}.md) "
|
||||
f"| {CLS_LABEL_ONE.get(cls_raw, cls_raw)} | {sys_str or '-'} | {file_str} "
|
||||
f"| {upstream_display} |"
|
||||
)
|
||||
@@ -163,23 +163,23 @@ def _render_xref_by_platform(
|
||||
config = cov["config"]
|
||||
count, rows = _xref_platform_rows(config, unique)
|
||||
stem = f"cross-reference-{pname}"
|
||||
if _own_list_only(config):
|
||||
if own_list_only(config):
|
||||
# cores: [] (MiSTer, BizHawk): no profile describes what they
|
||||
# read, and a page of cores would be an empty table.
|
||||
lines.append(f"| [{_escape_tags(display)}](platforms/{pname}.md) | 0 "
|
||||
lines.append(f"| [{escape_tags(display)}](platforms/{pname}.md) | 0 "
|
||||
f"| {OWN_LIST_ONLY} |")
|
||||
continue
|
||||
lines.append(
|
||||
f"| [{_escape_tags(display)}](platforms/{pname}.md) | {count}"
|
||||
f"{_core_scope_note(config, unique)} | [Cores on {_escape_tags(display)}]({stem}.md) |"
|
||||
f"| [{escape_tags(display)}](platforms/{pname}.md) | {count}"
|
||||
f"{_core_scope_note(config, unique)} | [Cores on {escape_tags(display)}]({stem}.md) |"
|
||||
)
|
||||
if moved is not None:
|
||||
moved[stem] = "\n".join([
|
||||
"---", "level: reference",
|
||||
*_parent_front_matter(("Cores by platform", "/cross-reference/")), "---", "",
|
||||
*parent_front_matter(("Cores by platform", "/cross-reference/")), "---", "",
|
||||
f"# Cores on {display}",
|
||||
"",
|
||||
f"{_count(count, 'core')}{_core_scope_note(config, unique)} that "
|
||||
f"{count_text(count, 'core')}{_core_scope_note(config, unique)} that "
|
||||
f"{display} runs, the systems each emulates and the project it comes "
|
||||
f"from. Part of [Cores by platform](cross-reference.md). The files "
|
||||
f"are listed on the [{display} page](platforms/{pname}.md).",
|
||||
@@ -236,7 +236,7 @@ def _render_xref_by_upstream(
|
||||
# The project's own address: the bare one when a core cites it.
|
||||
home = next((u for u in urls if not upstream_project(u)[1]), urls[0])
|
||||
upstream_cell = (f"[{_breakable(_upstream_label(key))}]({home})" if home.startswith("http")
|
||||
else _escape_tags(key))
|
||||
else escape_tags(key))
|
||||
lines.append(
|
||||
"| " + ", ".join(f"[{c}](emulators/{c}.md)" for c in cores)
|
||||
+ f" | {upstream_cell} | {', '.join(_breakable(r) for r in revisions) or '-'} "
|
||||
@@ -294,5 +294,5 @@ def generate_cross_reference(
|
||||
lines.extend(_render_xref_by_platform(coverages, unique, moved))
|
||||
lines.extend(_render_xref_by_upstream(coverages, unique))
|
||||
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
@@ -20,21 +20,22 @@ from model import retired as model_retired
|
||||
from model.dumpcatalog import load_provenance_snapshots
|
||||
from packs.crossref import FileConsumers
|
||||
from acquire.provenance import build_report
|
||||
from sitegen.apiitems import _sha1_by_path, core_index_items, system_index_items
|
||||
from sitegen.config import DATA_LICENSE, REPO_URL, _REPO_ROOT, _timestamp
|
||||
from sitegen.install import _release_pack_platforms
|
||||
from sitegen.apiitems import sha1_index_by_path, core_index_items, system_index_items
|
||||
from sitegen.config import DATA_LICENSE, REPO_URL, data_timestamp
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.install import release_pack_platforms
|
||||
from sitegen.lookup import (
|
||||
HASH_ALGORITHMS,
|
||||
_hash_values,
|
||||
sorted_hash_values,
|
||||
data_directory_members,
|
||||
file_location_items,
|
||||
file_lookup_records,
|
||||
write_lookup_shards,
|
||||
)
|
||||
from sitegen.provenance import load_derivable
|
||||
from sitegen.publish import _publish_manifests
|
||||
from sitegen.structured import _write_platform_dats, collection_dat
|
||||
from sitegen.write import _record, write_if_changed
|
||||
from sitegen.publish import publish_manifests
|
||||
from sitegen.structured import write_platform_dats, collection_dat
|
||||
from sitegen.write import record_written, write_if_changed
|
||||
|
||||
|
||||
def generate_stats(stats: dict) -> str:
|
||||
@@ -50,7 +51,7 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict])
|
||||
"layer": "platform", "owner": row["platform_id"],
|
||||
"system": row["system"], "name": row["name"],
|
||||
"path": row["destination"], "algorithm": algorithm, "value": value,
|
||||
} for value in _hash_values(row.get(f"{algorithm}_raw", row.get(algorithm))))
|
||||
} for value in sorted_hash_values(row.get(f"{algorithm}_raw", row.get(algorithm))))
|
||||
for item in emulator_items:
|
||||
for entry in item["profile"].get("files", []) or []:
|
||||
if not isinstance(entry, dict):
|
||||
@@ -61,7 +62,7 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict])
|
||||
"system": _json_text(entry.get("system")),
|
||||
"name": entry.get("name", ""), "path": entry.get("path", "") or "",
|
||||
"algorithm": algorithm, "value": value,
|
||||
} for value in _hash_values(entry.get(algorithm)))
|
||||
} for value in sorted_hash_values(entry.get(algorithm)))
|
||||
# Members of an archive: MAME and FBNeo hash the ROMs inside the
|
||||
# set, never the set. Left out, a loose nmk004.bin (crc32
|
||||
# 83b6f611) found no row while the site search found it.
|
||||
@@ -75,7 +76,7 @@ def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict])
|
||||
"system": _json_text(entry.get("system")),
|
||||
"name": str(member["name"]), "path": f"{archive}/{member['name']}",
|
||||
"algorithm": algorithm, "value": value,
|
||||
} for value in _hash_values(member.get(algorithm)))
|
||||
} for value in sorted_hash_values(member.get(algorithm)))
|
||||
rows.sort(key=lambda r: (r["layer"], r["owner"], r["name"], r["algorithm"], r["value"]))
|
||||
return rows
|
||||
|
||||
@@ -122,7 +123,7 @@ def _verify_outcomes(
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def _contract_keys() -> frozenset[str]:
|
||||
"""The top-level keys platform.schema.json allows in a platform's list."""
|
||||
schema = json.loads((_REPO_ROOT / "schemas" / "platform.schema.json").read_text(encoding="utf-8"))
|
||||
schema = json.loads((REPO_ROOT / "schemas" / "platform.schema.json").read_text(encoding="utf-8"))
|
||||
return frozenset(schema.get("properties") or {})
|
||||
|
||||
|
||||
@@ -159,7 +160,7 @@ def _split_contract(config: dict) -> tuple[dict, dict]:
|
||||
# The merged config gives a child its parent's release_pack: Lakka and
|
||||
# RetroPie said true in the API while every page said they had no ZIP.
|
||||
# The registry's own entry decides, as it does for the pages.
|
||||
released = config.get("_key") in _release_pack_platforms()
|
||||
released = config.get("_key") in release_pack_platforms()
|
||||
if released or "release_pack" in registry:
|
||||
registry["release_pack"] = released
|
||||
return contract, registry
|
||||
@@ -180,7 +181,7 @@ def _platform_export_rows(
|
||||
"""Normalized platform summaries and one row per declared file."""
|
||||
items: list[dict] = []
|
||||
file_rows: list[dict] = []
|
||||
sha1_by_path = _sha1_by_path(db)
|
||||
sha1_by_path = sha1_index_by_path(db)
|
||||
for key, coverage in sorted(coverages.items()):
|
||||
config = coverage["config"]
|
||||
outcome = _verify_outcomes(coverage, sha1_by_path)
|
||||
@@ -247,7 +248,7 @@ def build_emulator_gap_report(
|
||||
The gap analysis page and the published gaps export must not compute this
|
||||
twice and drift. Both read this one report.
|
||||
"""
|
||||
from model.systems import _norm_system_id
|
||||
from model.systems import norm_system_id
|
||||
from model.declarations import merged_platform_declarations
|
||||
from packs.crossref import cross_reference as run_cross_reference
|
||||
|
||||
@@ -263,7 +264,7 @@ def build_emulator_gap_report(
|
||||
for fe in system.get("files", []):
|
||||
fname = fe.get("name", "")
|
||||
if fname:
|
||||
declared.setdefault(_norm_system_id(sys_id), set()).add(fname)
|
||||
declared.setdefault(norm_system_id(sys_id), set()).add(fname)
|
||||
|
||||
unique_profiles = {
|
||||
k: v
|
||||
@@ -302,7 +303,7 @@ def _gap_export_rows(
|
||||
A `layer` column keeps the two apart instead of publishing only one.
|
||||
"""
|
||||
rows: list[dict] = []
|
||||
sha1_by_path = _sha1_by_path(db)
|
||||
sha1_by_path = sha1_index_by_path(db)
|
||||
for key, coverage in sorted(coverages.items()):
|
||||
for detail in coverage.get("details", []):
|
||||
if detail.get("status") == "ok" and not detail.get("discrepancy"):
|
||||
@@ -506,10 +507,10 @@ def _write_sqlite_export(
|
||||
CREATE INDEX emulator_files_name_idx ON emulator_files(name);
|
||||
CREATE INDEX gaps_status_idx ON gaps(layer, status);
|
||||
""")
|
||||
commit = _source_commit()
|
||||
commit = source_commit()
|
||||
metadata = {
|
||||
"schema_version": "1",
|
||||
"generated_at": str(db.get("generated_at") or _timestamp()),
|
||||
"generated_at": str(db.get("generated_at") or data_timestamp()),
|
||||
**({"commit": commit} if commit else {}),
|
||||
"source": REPO_URL,
|
||||
"scope": "metadata only, no BIOS or firmware payload bytes",
|
||||
@@ -640,13 +641,13 @@ def system_export_item(slug: str, manufacturer: str, consoles: dict[str, list])
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def _source_commit() -> str:
|
||||
def source_commit() -> str:
|
||||
"""The commit of the checkout the site is built from, empty outside one."""
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "rev-parse", "HEAD"], cwd=_REPO_ROOT,
|
||||
["git", "rev-parse", "HEAD"], cwd=REPO_ROOT,
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
except (OSError, subprocess.CalledProcessError) as error:
|
||||
@@ -694,10 +695,10 @@ def generate_data_exports(
|
||||
for directory in (api, downloads, schemas_dest):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
generated_at = str(db.get("generated_at") or _timestamp())
|
||||
generated_at = str(db.get("generated_at") or data_timestamp())
|
||||
# The revision the data was read at: a tool comparing two downloads
|
||||
# could not tell which commit each came from.
|
||||
commit = _source_commit()
|
||||
commit = source_commit()
|
||||
stamp = {"commit": commit} if commit else {}
|
||||
platform_items, platform_files = _platform_export_rows(coverages, db)
|
||||
emulator_items = _emulator_export_items(profiles)
|
||||
@@ -715,7 +716,7 @@ def generate_data_exports(
|
||||
}
|
||||
write_lookup_shards(
|
||||
api, file_lookup_records(db, coverages, profiles, locations, members, consumers,
|
||||
model_retired.load(_REPO_ROOT / "retired.json"), wanted),
|
||||
model_retired.load(REPO_ROOT / "retired.json"), wanted),
|
||||
generated_at, commit,
|
||||
)
|
||||
for filename, (kind, items) in envelopes.items():
|
||||
@@ -744,11 +745,11 @@ def generate_data_exports(
|
||||
|
||||
# Every schema the published files are written against, the manifests'
|
||||
# too: an integrator had the platform's list and not what the pack writes.
|
||||
for schema_path in sorted((_REPO_ROOT / "schemas").glob("*.schema.json")):
|
||||
for schema_path in sorted((REPO_ROOT / "schemas").glob("*.schema.json")):
|
||||
shutil.copy2(schema_path, schemas_dest / schema_path.name)
|
||||
_record(schemas_dest / schema_path.name)
|
||||
record_written(schemas_dest / schema_path.name)
|
||||
|
||||
manifest_assets = _publish_manifests(api)
|
||||
manifest_assets = publish_manifests(api)
|
||||
for filename, (kind, items) in {
|
||||
"systems.json": ("system-index", system_index_items(db, coverages, profiles)),
|
||||
"cores.json": ("core-index", core_index_items(profiles)),
|
||||
@@ -774,7 +775,7 @@ def generate_data_exports(
|
||||
),
|
||||
})
|
||||
write_if_changed(str(downloads / "retrobios.dat"), collection_dat(db, generated_at))
|
||||
platform_dats = _write_platform_dats(downloads / "dat", db, members, generated_at)
|
||||
platform_dats = write_platform_dats(downloads / "dat", db, members, generated_at)
|
||||
write_if_changed(
|
||||
str(downloads / "files.csv"),
|
||||
_csv_document(
|
||||
@@ -831,7 +832,7 @@ def generate_data_exports(
|
||||
downloads / "retrobios.sqlite", db, platform_items, platform_files,
|
||||
emulator_items, gap_rows,
|
||||
)
|
||||
_record(downloads / "retrobios.sqlite")
|
||||
record_written(downloads / "retrobios.sqlite")
|
||||
write_if_changed(
|
||||
str(downloads / "provenance-wanted.csv"),
|
||||
_csv_document(list(WANTED_FIELDS), wanted),
|
||||
|
||||
@@ -11,8 +11,9 @@ from model import siteinputs
|
||||
from model.registry import load_platform_registry
|
||||
from model.safeparse import yaml_load
|
||||
from sitegen import markup, measurements as sitemeasurements
|
||||
from sitegen.config import RELEASE_URL, REPO_URL, SITE_URL, _REPO_ROOT
|
||||
from sitegen.render import _escape_tags, _fmt_size
|
||||
from sitegen.config import RELEASE_URL, REPO_URL, SITE_URL
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.render import escape_tags, fmt_size
|
||||
|
||||
|
||||
def _is_manifest(item: dict) -> bool:
|
||||
@@ -36,7 +37,7 @@ def _served_schemas() -> list[tuple[str, str]]:
|
||||
the export copies: the page linked 7 of 11."""
|
||||
return [
|
||||
(path.name, str(json.loads(path.read_text(encoding="utf-8")).get("title") or path.stem))
|
||||
for path in sorted((_REPO_ROOT / "schemas").glob("*.schema.json"))
|
||||
for path in sorted((REPO_ROOT / "schemas").glob("*.schema.json"))
|
||||
]
|
||||
|
||||
|
||||
@@ -55,7 +56,7 @@ def _schema_field_rows(schema: dict, keys: tuple[str, ...]) -> list[str]:
|
||||
text = str((props.get(key) or {}).get("description") or "")
|
||||
if text:
|
||||
# Python before 3.12 refuses a backslash inside an f-string expression.
|
||||
described = _escape_tags(_URL_TEMPLATE.sub(r"`\g<0>`", text))
|
||||
described = escape_tags(_URL_TEMPLATE.sub(r"`\g<0>`", text))
|
||||
rows.append(f"| `{key}` | {described} |")
|
||||
return rows
|
||||
|
||||
@@ -132,8 +133,8 @@ def _join_names(names: list[str]) -> str:
|
||||
|
||||
def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = None) -> str:
|
||||
manifest_schema = json.loads(
|
||||
(_REPO_ROOT / "schemas" / "install-manifest.schema.json").read_text(encoding="utf-8"))
|
||||
snippet = (_REPO_ROOT / "scripts" / "check_platform_folder.py").read_text(encoding="utf-8")
|
||||
(REPO_ROOT / "schemas" / "install-manifest.schema.json").read_text(encoding="utf-8"))
|
||||
snippet = (REPO_ROOT / "scripts" / "check_platform_folder.py").read_text(encoding="utf-8")
|
||||
manifests = [item for item in exports if _is_manifest(item)]
|
||||
targets = [item for item in exports if _is_target_list(item)]
|
||||
no_list = _platforms_without_a_list()
|
||||
@@ -177,7 +178,7 @@ def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = N
|
||||
)
|
||||
lines.append(
|
||||
f"| {item['title']} | [`{item['url']}`]({item['url']}) | "
|
||||
f"{schema} | {_fmt_size(item['bytes'])} |"
|
||||
f"{schema} | {fmt_size(item['bytes'])} |"
|
||||
)
|
||||
lines.extend([
|
||||
"",
|
||||
@@ -353,7 +354,7 @@ def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = N
|
||||
continue
|
||||
lines.append(
|
||||
f"| [{item['title']}]({item['url']}) | `{item['media_type']}` | "
|
||||
f"{_fmt_size(item['bytes'])} | {_short_sha256(item, 'api/v1/catalog.json')} |"
|
||||
f"{fmt_size(item['bytes'])} | {_short_sha256(item, 'api/v1/catalog.json')} |"
|
||||
)
|
||||
lines.extend([
|
||||
"",
|
||||
|
||||
+12
-11
@@ -12,11 +12,12 @@ from model import releaserecord
|
||||
from model import siteinputs
|
||||
from model.database import load_database
|
||||
from sitegen import markup, measurements as sitemeasurements, starlight as sitestarlight
|
||||
from sitegen.config import SITE_NAME, SITE_URL, _REPO_ROOT, yaml
|
||||
from sitegen.descriptions import PAGE_DATA, _browser_title, _page_description, _page_title
|
||||
from sitegen.config import SITE_NAME, SITE_URL, yaml
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.descriptions import PAGE_DATA, page_browser_title, page_description, page_title
|
||||
from sitegen.diagrams import prepare_page, unresolved_images
|
||||
from sitegen.render import WIKI_SRC_DIR
|
||||
from sitegen.write import _undecorated, write_decorated
|
||||
from sitegen.write import undecorated, write_decorated
|
||||
|
||||
|
||||
# Working notes kept under docs/ during development, never part of the site,
|
||||
@@ -99,7 +100,7 @@ def level_label(level: str) -> str:
|
||||
return f'<span class="rb-level rb-level-{level}">{LEVELS[level]}</span>'
|
||||
|
||||
|
||||
def _front_matter(markdown: str) -> dict:
|
||||
def front_matter(markdown: str) -> dict:
|
||||
"""The YAML front matter of a page, empty when it has none."""
|
||||
if not markdown.startswith("---\n"):
|
||||
return {}
|
||||
@@ -138,13 +139,13 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]:
|
||||
returned by address, for the sitemap.
|
||||
"""
|
||||
lastmod: dict[str, str] = {}
|
||||
terms = sitestarlight.glossary_terms(_REPO_ROOT / WIKI_SRC_DIR / "glossary.md")
|
||||
terms = sitestarlight.glossary_terms(REPO_ROOT / WIKI_SRC_DIR / "glossary.md")
|
||||
# The console words of every system page, decorated or not: a console
|
||||
# another page's words cover gets a search field of its own.
|
||||
console_words: dict[str, set[str]] = {}
|
||||
for path in sorted((docs / "systems").glob("*.md*")):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
words = sitestarlight.page_console_words(_front_matter(text), text)
|
||||
words = sitestarlight.page_console_words(front_matter(text), text)
|
||||
if words:
|
||||
console_words[path.relative_to(docs).with_suffix("").as_posix()] = words
|
||||
for path in sorted(docs.rglob("*.md")):
|
||||
@@ -152,7 +153,7 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]:
|
||||
if any(part in LOCAL_NOTE_DIRS for part in relative.parts[:-1]):
|
||||
continue
|
||||
original = path.read_text(encoding="utf-8")
|
||||
authored = _front_matter(original)
|
||||
authored = front_matter(original)
|
||||
if "head" in authored:
|
||||
# Written in its final form by an earlier pass and rewritten by
|
||||
# nothing since: a second pass would find no title to read.
|
||||
@@ -160,7 +161,7 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]:
|
||||
markdown = _cards_elsewhere(prepare_page(original, relative))
|
||||
for image_id in unresolved_images(markdown):
|
||||
print(f" WARNING: {relative}: no diagram named {image_id!r}", file=sys.stderr)
|
||||
stripped = _undecorated(markdown)
|
||||
stripped = undecorated(markdown)
|
||||
if stripped is not markdown:
|
||||
markdown = stripped
|
||||
elif authored:
|
||||
@@ -168,9 +169,9 @@ def decorate_markdown_pages(docs: Path) -> dict[str, str]:
|
||||
markdown = markdown[markdown.find("\n---\n", 4) + 5:].lstrip("\n")
|
||||
level = authored.get("level") or page_level(relative)
|
||||
|
||||
title = _page_title(markdown, relative)
|
||||
browser_title = _browser_title(relative, title)
|
||||
description = str(authored.get("description") or _page_description(markdown, relative, title))
|
||||
title = page_title(markdown, relative)
|
||||
browser_title = page_browser_title(relative, title)
|
||||
description = str(authored.get("description") or page_description(markdown, relative, title))
|
||||
if relative.name == "index.md":
|
||||
page_path = "" if len(relative.parts) == 1 else "/".join(relative.parts[:-1]) + "/"
|
||||
else:
|
||||
|
||||
@@ -11,7 +11,7 @@ from sitegen import measurements as sitemeasurements
|
||||
from sitegen.config import SITE_NAME
|
||||
|
||||
|
||||
def _page_title(markdown: str, path: Path) -> str:
|
||||
def page_title(markdown: str, path: Path) -> str:
|
||||
match = re.search(r"^#\s+(.+?)\s*$", markdown, flags=re.MULTILINE)
|
||||
if match:
|
||||
title = re.sub(r"<[^>]+>", "", match.group(1))
|
||||
@@ -19,7 +19,7 @@ def _page_title(markdown: str, path: Path) -> str:
|
||||
return path.stem.replace("-", " ").title()
|
||||
|
||||
|
||||
def _browser_title(relative: Path, title: str) -> str:
|
||||
def page_browser_title(relative: Path, title: str) -> str:
|
||||
"""Return a concise, unique browser/search title for a generated page."""
|
||||
key = relative.as_posix()
|
||||
index_titles = {
|
||||
@@ -84,7 +84,7 @@ def _shorten(plain: str, limit: int = 157) -> str:
|
||||
return cut.rstrip(" ,;:-(.") + "..."
|
||||
|
||||
|
||||
def _page_description(markdown: str, relative: Path, title: str) -> str:
|
||||
def page_description(markdown: str, relative: Path, title: str) -> str:
|
||||
key = relative.as_posix()
|
||||
specific = {
|
||||
"index.md": "The BIOS files emulators need, for RetroArch, Batocera, EmuDeck and more: the folder they go in, one command that installs and checks them, and packs to download.",
|
||||
@@ -103,7 +103,7 @@ def _page_description(markdown: str, relative: Path, title: str) -> str:
|
||||
return specific[key]
|
||||
# What a search engine shows is the page's own first sentence: 707 pages
|
||||
# shared five templates of level 3 words ("source-pinned", "provenance").
|
||||
browser = _browser_title(relative, title)
|
||||
browser = page_browser_title(relative, title)
|
||||
held = re.search(r"\bThis part holds (.+?)\.(?: |$)", markdown, re.M)
|
||||
if key in PART_PAGES and held:
|
||||
return _shorten(f"{browser}. This part holds {_plain_markdown(held[1])}.", 155)
|
||||
@@ -226,7 +226,7 @@ def _files_snippet(markdown: str, key: str, title: str, intro: str) -> str:
|
||||
for count in range(min(len(names), 4), 0, -1):
|
||||
shown = (names if count == len(names)
|
||||
else [*names[:count - 1], f"{len(names) - count + 1:,} more"])
|
||||
head = f"{subject}: {_said_as_list(shown)}, {need}."
|
||||
head = f"{subject}: {said_as_list(shown)}, {need}."
|
||||
forms += [f"{head} {tail}" for tail in tails if tail] + [head]
|
||||
return next((form for form in forms if len(form) <= 155), intro)
|
||||
|
||||
@@ -271,7 +271,7 @@ def _system_description(markdown: str, browser: str) -> str:
|
||||
consoles = [name for name in consoles if name and name not in _NOT_A_CONSOLE]
|
||||
if len(consoles) > 1:
|
||||
shown = consoles if len(consoles) <= 4 else consoles[:3] + [f"{len(consoles) - 3} more"]
|
||||
return _shorten(f"{browser} for {_said_as_list(shown)}, one card per file with its "
|
||||
return _shorten(f"{browser} for {said_as_list(shown)}, one card per file with its "
|
||||
"hashes and the emulators that read it.", 155)
|
||||
start = re.search(r"^\*\*Start with\*\*(?P<line>.*)$(?P<list>(?:\n+- .*)*)", markdown, re.M)
|
||||
if start:
|
||||
@@ -283,7 +283,7 @@ def _system_description(markdown: str, browser: str) -> str:
|
||||
names = list(dict.fromkeys(html.unescape(name) for name in _CARD_TITLE.findall(markdown)))
|
||||
if names:
|
||||
shown = names if len(names) <= 3 else names[:3] + [f"{len(names) - 3} more"]
|
||||
return _shorten(f"{browser}: {_said_as_list(shown)}, with their hashes and the "
|
||||
return _shorten(f"{browser}: {said_as_list(shown)}, with their hashes and the "
|
||||
"emulators that read them.", 155)
|
||||
return _shorten(f"{browser}, one card per file with its hashes and the emulators "
|
||||
"that read it.", 155)
|
||||
@@ -304,6 +304,6 @@ EMULATOR_SNIPPETS: dict[str, tuple[str, list[str], int, str]] = {}
|
||||
PART_PAGES: set[str] = set()
|
||||
|
||||
|
||||
def _said_as_list(items: list[str]) -> str:
|
||||
def said_as_list(items: list[str]) -> str:
|
||||
""""a, b and c"."""
|
||||
return ", ".join(items[:-1]) + f" and {items[-1]}" if len(items) > 1 else "".join(items)
|
||||
+56
-58
@@ -18,8 +18,6 @@ from model import siteinputs
|
||||
from sitegen import markup
|
||||
|
||||
|
||||
ROOT = REPO_ROOT
|
||||
|
||||
PLACEHOLDER = re.compile(r"(?m)^([ \t]*)<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->[ \t]*$")
|
||||
PLACEHOLDER_ANYWHERE = re.compile(r"<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->")
|
||||
|
||||
@@ -76,7 +74,7 @@ def wrap(text: str, width: float, size: float, bold: bool = False) -> list[str]:
|
||||
return lines
|
||||
|
||||
|
||||
def _n(value: float) -> str:
|
||||
def svg_number(value: float) -> str:
|
||||
text = f"{value:.1f}"
|
||||
return text[:-2] if text.endswith(".0") else text
|
||||
|
||||
@@ -104,48 +102,48 @@ class Figure:
|
||||
# Drawing primitives
|
||||
|
||||
|
||||
def _text(x: float, y: float, value: str, size: float = TEXT_SIZE,
|
||||
def svg_text(x: float, y: float, value: str, size: float = TEXT_SIZE,
|
||||
bold: bool = False, anchor: str = "start", cls: str = "") -> str:
|
||||
weight = ' font-weight="600"' if bold else ""
|
||||
klass = f' class="{cls}"' if cls else ""
|
||||
style = f' style="{MONO_STYLE}"' if isinstance(value, Mono) else ""
|
||||
fill = MUTED if cls == "rb-d-muted" else ("#ffffff" if cls == "rb-d-numtext" else INK)
|
||||
return (
|
||||
f'<text x="{_n(x)}" y="{_n(y)}" font-size="{_n(size)}"{weight} '
|
||||
f'<text x="{svg_number(x)}" y="{svg_number(y)}" font-size="{svg_number(size)}"{weight} '
|
||||
f'text-anchor="{anchor}" fill="{fill}"{klass}{style}>{escape(value)}</text>'
|
||||
)
|
||||
|
||||
|
||||
def _rect(x: float, y: float, w: float, h: float, accent: bool = False) -> str:
|
||||
def svg_rect(x: float, y: float, w: float, h: float, accent: bool = False) -> str:
|
||||
cls = "rb-d-box rb-d-accent" if accent else "rb-d-box"
|
||||
stroke = ACCENT if accent else STROKE
|
||||
width = 2 if accent else 1
|
||||
return (
|
||||
f'<rect x="{_n(x)}" y="{_n(y)}" width="{_n(w)}" height="{_n(h)}" rx="4" '
|
||||
f'<rect x="{svg_number(x)}" y="{svg_number(y)}" width="{svg_number(w)}" height="{svg_number(h)}" rx="4" '
|
||||
f'fill="{FILL}" stroke="{stroke}" stroke-width="{width}" class="{cls}"/>'
|
||||
)
|
||||
|
||||
|
||||
def _badge_side(number: str) -> float:
|
||||
def badge_side(number: str) -> float:
|
||||
return max(20.0, _width(number, 11, True) + 10)
|
||||
|
||||
|
||||
def _badge(x: float, y: float, number: str) -> list[str]:
|
||||
side = _badge_side(number)
|
||||
def badge(x: float, y: float, number: str) -> list[str]:
|
||||
side = badge_side(number)
|
||||
return [
|
||||
f'<rect x="{_n(x)}" y="{_n(y)}" width="{_n(side)}" height="20" rx="3" '
|
||||
f'<rect x="{svg_number(x)}" y="{svg_number(y)}" width="{svg_number(side)}" height="20" rx="3" '
|
||||
f'fill="{ACCENT}" class="rb-d-num"/>',
|
||||
_text(x + side / 2, y + 14, number, 11, True, "middle", "rb-d-numtext"),
|
||||
svg_text(x + side / 2, y + 14, number, 11, True, "middle", "rb-d-numtext"),
|
||||
]
|
||||
|
||||
|
||||
def _line(points: list[tuple[float, float]], head: bool = True) -> list[str]:
|
||||
def svg_connector(points: list[tuple[float, float]], head: bool = True) -> list[str]:
|
||||
"""A connector through *points*, with a drawn arrowhead at the end.
|
||||
|
||||
The head is a small triangle, never a text glyph.
|
||||
"""
|
||||
path = " ".join(
|
||||
f"{'M' if index == 0 else 'L'}{_n(x)} {_n(y)}" for index, (x, y) in enumerate(points)
|
||||
f"{'M' if index == 0 else 'L'}{svg_number(x)} {svg_number(y)}" for index, (x, y) in enumerate(points)
|
||||
)
|
||||
out = [
|
||||
f'<path d="{path}" fill="none" stroke="{STROKE}" stroke-width="1.5" class="rb-d-line"/>'
|
||||
@@ -159,7 +157,7 @@ def _line(points: list[tuple[float, float]], head: bool = True) -> list[str]:
|
||||
sign = 1 if x2 > x1 else -1
|
||||
tri = [(x2, y2), (x2 - 8 * sign, y2 - 5), (x2 - 8 * sign, y2 + 5)]
|
||||
out.append(
|
||||
'<path d="M' + " L".join(f"{_n(x)} {_n(y)}" for x, y in tri)
|
||||
'<path d="M' + " L".join(f"{svg_number(x)} {svg_number(y)}" for x, y in tri)
|
||||
+ f' Z" fill="{STROKE}" class="rb-d-head"/>'
|
||||
)
|
||||
return out
|
||||
@@ -168,7 +166,7 @@ def _line(points: list[tuple[float, float]], head: bool = True) -> list[str]:
|
||||
def box_lines(box: Box, width: float) -> tuple[list[str], list[str]]:
|
||||
"""The title and body lines of *box* drawn *width* wide, as wrapped."""
|
||||
inner = width - 2 * PAD
|
||||
title_lines = wrap(box.title, inner - (_badge_side(box.number) + 8 if box.number else 0),
|
||||
title_lines = wrap(box.title, inner - (badge_side(box.number) + 8 if box.number else 0),
|
||||
TITLE_SIZE, True)
|
||||
body: list[str] = []
|
||||
for line in box.lines:
|
||||
@@ -186,18 +184,18 @@ def _box_height(box: Box, width: float) -> tuple[list[str], list[str], float]:
|
||||
|
||||
def _draw_box(box: Box, x: float, y: float, width: float, height: float,
|
||||
title_lines: list[str], body: list[str]) -> list[str]:
|
||||
out = [_rect(x, y, width, height, box.accent)]
|
||||
out = [svg_rect(x, y, width, height, box.accent)]
|
||||
tx = x + PAD
|
||||
if box.number:
|
||||
out.extend(_badge(x + PAD, y + PAD, box.number))
|
||||
tx += _badge_side(box.number) + 8
|
||||
out.extend(badge(x + PAD, y + PAD, box.number))
|
||||
tx += badge_side(box.number) + 8
|
||||
cy = y + PAD + 15
|
||||
for line in title_lines:
|
||||
out.append(_text(tx, cy, line, TITLE_SIZE, True))
|
||||
out.append(svg_text(tx, cy, line, TITLE_SIZE, True))
|
||||
cy += LINE
|
||||
cy += 6
|
||||
for line in body:
|
||||
out.append(_text(x + PAD, cy, line, TEXT_SIZE, cls="rb-d-muted"))
|
||||
out.append(svg_text(x + PAD, cy, line, TEXT_SIZE, cls="rb-d-muted"))
|
||||
cy += LINE
|
||||
return out
|
||||
|
||||
@@ -214,7 +212,7 @@ def flow(boxes: list[Box], vertical: bool, total: float) -> tuple[float, float,
|
||||
out.extend(_draw_box(box, 1, y, width - 2, height, title_lines, body))
|
||||
y += height
|
||||
if index < len(boxes) - 1:
|
||||
out.extend(_line([(width / 2, y), (width / 2, y + 22)]))
|
||||
out.extend(svg_connector([(width / 2, y), (width / 2, y + 22)]))
|
||||
y += 24
|
||||
return width, y + 1, out
|
||||
gap = 26.0
|
||||
@@ -228,7 +226,7 @@ def flow(boxes: list[Box], vertical: bool, total: float) -> tuple[float, float,
|
||||
out.extend(_draw_box(box, x, 1, width, height, title_lines, body))
|
||||
if index < len(boxes) - 1:
|
||||
mid = 1 + height / 2
|
||||
out.extend(_line([(x + width, mid), (x + width + gap - 1, mid)]))
|
||||
out.extend(svg_connector([(x + width, mid), (x + width + gap - 1, mid)]))
|
||||
return total, height + 2, out
|
||||
|
||||
|
||||
@@ -267,11 +265,11 @@ def grid(boxes: list[Box], per_row: int, total: float) -> tuple[float, float, li
|
||||
x = 1 + index * (width + gap_x)
|
||||
if previous_end is not None and index == 0:
|
||||
px, py = previous_end
|
||||
out.extend(_line([(px, py), (px, py + gap_y / 2), (x + width / 2, py + gap_y / 2),
|
||||
out.extend(svg_connector([(px, py), (px, py + gap_y / 2), (x + width / 2, py + gap_y / 2),
|
||||
(x + width / 2, y)]))
|
||||
out.extend(_draw_box(box, x, y, width, height, title_lines, body))
|
||||
if index < len(row) - 1:
|
||||
out.extend(_line([(x + width, y + height / 2), (x + width + gap_x - 1, y + height / 2)]))
|
||||
out.extend(svg_connector([(x + width, y + height / 2), (x + width + gap_x - 1, y + height / 2)]))
|
||||
previous_end = (x + width / 2, y + height)
|
||||
y += height + gap_y
|
||||
return total, y - gap_y + 1, out
|
||||
@@ -281,8 +279,8 @@ def svg_document(width: float, height: float, title: str, desc: str, body: list[
|
||||
base: str) -> str:
|
||||
"""A drawing as a standalone, accessible SVG element."""
|
||||
return (
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {_n(width)} {_n(height)}" '
|
||||
f'width="{_n(width)}" height="{_n(height)}" role="img" '
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {svg_number(width)} {svg_number(height)}" '
|
||||
f'width="{svg_number(width)}" height="{svg_number(height)}" role="img" '
|
||||
f'aria-labelledby="{base}-t {base}-d" font-family="{FONT}">'
|
||||
f'<title id="{base}-t">{escape(title)}</title>'
|
||||
f'<desc id="{base}-d">{escape(desc)}</desc>'
|
||||
@@ -539,7 +537,7 @@ MINUI_EXAMPLES = (("Sony PlayStation", "PS"), ("Game Boy Advance", "GBA"), ("Seg
|
||||
|
||||
@cache
|
||||
def minui_files() -> dict[str, list[str]]:
|
||||
manifest = json.loads((ROOT / "install" / "minui.json").read_text(encoding="utf-8"))
|
||||
manifest = json.loads((REPO_ROOT / "install" / "minui.json").read_text(encoding="utf-8"))
|
||||
by_tag: dict[str, list[str]] = {}
|
||||
for entry in manifest.get("files", []):
|
||||
parts = str(entry.get("dest", "")).split("/")
|
||||
@@ -551,23 +549,23 @@ def minui_files() -> dict[str, list[str]]:
|
||||
def _minui_wide() -> tuple[float, float, list[str]]:
|
||||
out: list[str] = []
|
||||
left_x, right_x, row = 1.0, 430.0, 22.0
|
||||
out.append(_text(left_x, 16, "Roms/", TITLE_SIZE, True))
|
||||
out.append(_text(right_x, 16, "Bios/", TITLE_SIZE, True))
|
||||
out.append(svg_text(left_x, 16, "Roms/", TITLE_SIZE, True))
|
||||
out.append(svg_text(right_x, 16, "Bios/", TITLE_SIZE, True))
|
||||
y = 30.0
|
||||
for name, tag in MINUI_EXAMPLES:
|
||||
files = minui_files().get(tag, [])
|
||||
shown = files[:2] + ([f"and {len(files) - 2} more"] if len(files) > 2 else [])
|
||||
height = max(row + 8, 14 + row * (1 + len(shown)))
|
||||
label = f"{name} ({tag})/"
|
||||
out.append(_rect(left_x + 14, y, 250, row + 8))
|
||||
out.append(_text(left_x + 24, y + 19, label, TEXT_SIZE, True))
|
||||
out.append(_rect(right_x + 14, y, 250, height))
|
||||
out.append(_text(right_x + 24, y + 19, f"{tag}/", TEXT_SIZE, True))
|
||||
out.append(svg_rect(left_x + 14, y, 250, row + 8))
|
||||
out.append(svg_text(left_x + 24, y + 19, label, TEXT_SIZE, True))
|
||||
out.append(svg_rect(right_x + 14, y, 250, height))
|
||||
out.append(svg_text(right_x + 24, y + 19, f"{tag}/", TEXT_SIZE, True))
|
||||
for index, file_name in enumerate(shown):
|
||||
out.append(_text(right_x + 40, y + 19 + row * (index + 1), file_name, TEXT_SIZE,
|
||||
out.append(svg_text(right_x + 40, y + 19 + row * (index + 1), file_name, TEXT_SIZE,
|
||||
cls="rb-d-muted"))
|
||||
out.extend(_line([(left_x + 264, y + (row + 8) / 2), (right_x + 13, y + (row + 8) / 2)]))
|
||||
out.append(_text((left_x + 264 + right_x + 14) / 2, y + (row + 8) / 2 - 6,
|
||||
out.extend(svg_connector([(left_x + 264, y + (row + 8) / 2), (right_x + 13, y + (row + 8) / 2)]))
|
||||
out.append(svg_text((left_x + 264 + right_x + 14) / 2, y + (row + 8) / 2 - 6,
|
||||
f"tag {tag}", 11, anchor="middle", cls="rb-d-muted"))
|
||||
y += height + 14
|
||||
return WIDE, y - 12, out
|
||||
@@ -578,10 +576,10 @@ def _minui_narrow() -> tuple[float, float, list[str]]:
|
||||
y = 1.0
|
||||
for name, tag in MINUI_EXAMPLES:
|
||||
files = minui_files().get(tag, [])
|
||||
out.append(_rect(1, y, NARROW - 2, 30))
|
||||
out.append(_text(11, y + 20, f"Roms/{name} ({tag})/", TEXT_SIZE, True))
|
||||
out.extend(_line([(NARROW / 2, y + 30), (NARROW / 2, y + 52)]))
|
||||
out.append(_text(NARROW / 2 + 10, y + 45, f"tag {tag}", 11, cls="rb-d-muted"))
|
||||
out.append(svg_rect(1, y, NARROW - 2, 30))
|
||||
out.append(svg_text(11, y + 20, f"Roms/{name} ({tag})/", TEXT_SIZE, True))
|
||||
out.extend(svg_connector([(NARROW / 2, y + 30), (NARROW / 2, y + 52)]))
|
||||
out.append(svg_text(NARROW / 2 + 10, y + 45, f"tag {tag}", 11, cls="rb-d-muted"))
|
||||
y += 54
|
||||
detail = ""
|
||||
if len(files) == 1:
|
||||
@@ -589,17 +587,17 @@ def _minui_narrow() -> tuple[float, float, list[str]]:
|
||||
elif files:
|
||||
detail = f"{len(files)} files, such as {files[0]}"
|
||||
height = 30 + (LINE if detail else 0)
|
||||
out.append(_rect(1, y, NARROW - 2, height, accent=True))
|
||||
out.append(_text(11, y + 20, f"Bios/{tag}/", TEXT_SIZE, True))
|
||||
out.append(svg_rect(1, y, NARROW - 2, height, accent=True))
|
||||
out.append(svg_text(11, y + 20, f"Bios/{tag}/", TEXT_SIZE, True))
|
||||
if detail:
|
||||
out.append(_text(11, y + 20 + LINE, detail, TEXT_SIZE, cls="rb-d-muted"))
|
||||
out.append(svg_text(11, y + 20 + LINE, detail, TEXT_SIZE, cls="rb-d-muted"))
|
||||
y += height + 18
|
||||
return NARROW, y - 17, out
|
||||
|
||||
|
||||
def _pipeline_boxes() -> list[Box]:
|
||||
"""The steps pipeline.py runs, read from its STEP_LABELS literal."""
|
||||
tree = ast.parse((ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"))
|
||||
tree = ast.parse((REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Assign):
|
||||
target: ast.expr = node.targets[0]
|
||||
@@ -638,15 +636,15 @@ def _layers(vertical: bool) -> tuple[float, float, list[str]]:
|
||||
px, py, pw, ph = place(platform, 1, 1, 200)
|
||||
sx, sy, sw, sh = place(shared, 1, py + ph + 26, 200)
|
||||
ex, ey, ew, eh = place(profiles, 1, sy + sh + 26, 200)
|
||||
out.extend(_line([(sx + sw / 2, sy), (px + pw / 2, py + ph)]))
|
||||
out.extend(_line([(sx + sw / 2, sy + sh), (ex + ew / 2, ey)]))
|
||||
out.extend(svg_connector([(sx + sw / 2, sy), (px + pw / 2, py + ph)]))
|
||||
out.extend(svg_connector([(sx + sw / 2, sy + sh), (ex + ew / 2, ey)]))
|
||||
_, _, pack_h = _box_height(pack, 200)
|
||||
gx, gy, gw, gh = place(pack, 270, sy + (sh - pack_h) / 2, 200)
|
||||
out.extend(_line([(px + pw, py + ph / 2), (240, py + ph / 2), (240, gy + 20), (gx - 1, gy + 20)]))
|
||||
out.extend(_line([(ex + ew, ey + eh / 2), (240, ey + eh / 2), (240, gy + gh - 20),
|
||||
out.extend(svg_connector([(px + pw, py + ph / 2), (240, py + ph / 2), (240, gy + 20), (gx - 1, gy + 20)]))
|
||||
out.extend(svg_connector([(ex + ew, ey + eh / 2), (240, ey + eh / 2), (240, gy + gh - 20),
|
||||
(gx - 1, gy + gh - 20)]))
|
||||
zx, zy, zw, zh = place(zip_box, 518, gy + (gh - 42) / 2, 200)
|
||||
out.extend(_line([(gx + gw, gy + gh / 2), (zx - 1, gy + gh / 2)]))
|
||||
out.extend(svg_connector([(gx + gw, gy + gh / 2), (zx - 1, gy + gh / 2)]))
|
||||
return WIDE, max(ey + eh, gy + gh) + 2, out
|
||||
|
||||
w = NARROW - 2
|
||||
@@ -654,14 +652,14 @@ def _layers(vertical: bool) -> tuple[float, float, list[str]]:
|
||||
sx, sy, sw, sh = place(shared, 1, 1, w)
|
||||
px, py, pw, ph = place(platform, 1, sy + sh + 26, half)
|
||||
ex, ey, ew, eh = place(profiles, 15 + half, py, half)
|
||||
out.extend(_line([(px + pw / 2, sy + sh), (px + pw / 2, py)]))
|
||||
out.extend(_line([(ex + ew / 2, sy + sh), (ex + ew / 2, ey)]))
|
||||
out.extend(svg_connector([(px + pw / 2, sy + sh), (px + pw / 2, py)]))
|
||||
out.extend(svg_connector([(ex + ew / 2, sy + sh), (ex + ew / 2, ey)]))
|
||||
bottom = max(py + ph, ey + eh)
|
||||
gx, gy, gw, gh = place(pack, 1, bottom + 26, w)
|
||||
out.extend(_line([(px + pw / 2, py + ph), (px + pw / 2, gy)]))
|
||||
out.extend(_line([(ex + ew / 2, ey + eh), (ex + ew / 2, gy)]))
|
||||
out.extend(svg_connector([(px + pw / 2, py + ph), (px + pw / 2, gy)]))
|
||||
out.extend(svg_connector([(ex + ew / 2, ey + eh), (ex + ew / 2, gy)]))
|
||||
zx, zy, zw, zh = place(zip_box, 1, gy + gh + 26, w)
|
||||
out.extend(_line([(NARROW / 2, gy + gh), (NARROW / 2, zy)]))
|
||||
out.extend(svg_connector([(NARROW / 2, gy + gh), (NARROW / 2, zy)]))
|
||||
return NARROW, zy + zh + 2, out
|
||||
|
||||
|
||||
@@ -791,8 +789,8 @@ def unresolved_images(markdown: str) -> list[str]:
|
||||
|
||||
# Local copies of images the site used to load from other hosts.
|
||||
|
||||
LOGO_DIR = ROOT / "docs_assets" / "logos"
|
||||
ICON_DIR = ROOT / "docs_assets" / "system-icons"
|
||||
LOGO_DIR = REPO_ROOT / "docs_assets" / "logos"
|
||||
ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons"
|
||||
SITE_LOGO_DIR = "assets/logos"
|
||||
SITE_ICON_DIR = "assets/system-icons"
|
||||
IMAGE_LINK = re.compile(r"(!\[[^\]\n]*\]\()(https?://[^)\s]+)(\))")
|
||||
@@ -912,7 +910,7 @@ def _string(node: ast.expr, constants: dict[str, str]) -> str:
|
||||
@cache
|
||||
def installer_options() -> tuple[tuple[str, str], ...]:
|
||||
"""(usage, help) for each option of install.py, in the order --help lists them."""
|
||||
tree = ast.parse((ROOT / "install.py").read_text(encoding="utf-8"))
|
||||
tree = ast.parse((REPO_ROOT / "install.py").read_text(encoding="utf-8"))
|
||||
constants = {
|
||||
node.targets[0].id: node.value.value
|
||||
for node in tree.body
|
||||
|
||||
@@ -10,7 +10,7 @@ from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from model.collection import _slug
|
||||
from model.collection import manufacturer_slug
|
||||
from model.systemnames import system_name
|
||||
from packs.crossref import FileConsumers, entry_target, held_copy
|
||||
from resolve.cores import resolve_platform_cores
|
||||
@@ -19,37 +19,37 @@ from sitegen.cards import (
|
||||
ROMSET_FAQ,
|
||||
SEARCH_SKIPPED,
|
||||
SHORT_HASH,
|
||||
_card_title,
|
||||
_listed_words,
|
||||
_places_markdown,
|
||||
_platform_links,
|
||||
_platform_places,
|
||||
_search_skipped_apart,
|
||||
card_title,
|
||||
listed_words,
|
||||
places_markdown,
|
||||
platform_links,
|
||||
platform_places,
|
||||
search_skipped_apart,
|
||||
card_fold,
|
||||
)
|
||||
from sitegen.config import REPO_URL
|
||||
from sitegen.descriptions import _said_as_list
|
||||
from sitegen.fields import _hash_spans
|
||||
from sitegen.descriptions import said_as_list
|
||||
from sitegen.fields import hash_spans
|
||||
from sitegen.install import (
|
||||
_OS_LABELS,
|
||||
_platform_display,
|
||||
_under_root,
|
||||
OS_LABELS,
|
||||
platform_display,
|
||||
under_root,
|
||||
comes_with_app,
|
||||
data_root_words,
|
||||
standalone_place,
|
||||
)
|
||||
from sitegen.render import (
|
||||
WIKI_SRC_DIR,
|
||||
_code,
|
||||
_count,
|
||||
_escape_tags,
|
||||
_fmt_size,
|
||||
code_span,
|
||||
count_text,
|
||||
escape_tags,
|
||||
fmt_size,
|
||||
card_page,
|
||||
console_href,
|
||||
)
|
||||
from sitegen.sources import (
|
||||
_source_permalink,
|
||||
_source_ref_markdown,
|
||||
source_permalink,
|
||||
source_ref_markdown,
|
||||
link_prose_citations,
|
||||
requested_by,
|
||||
version_basis_url,
|
||||
@@ -59,7 +59,7 @@ from sitegen.sources import (
|
||||
# Emulator pages
|
||||
|
||||
|
||||
def _named_system_link(sys_id: str, prefix: str = "") -> str:
|
||||
def named_system_link(sys_id: str, prefix: str = "") -> str:
|
||||
"""A system by its display name, linked where _system_link links it.
|
||||
|
||||
The emulator pages printed the id ("sony-playstation") where every
|
||||
@@ -79,7 +79,7 @@ def _named_system_link(sys_id: str, prefix: str = "") -> str:
|
||||
_REGION_WORDS = {"world": "every region"}
|
||||
|
||||
|
||||
def _region_words(value: object, most: int = 0) -> str:
|
||||
def region_words(value: object, most: int = 0) -> str:
|
||||
"""A region: value in words. ``most`` caps the regions named, the rest
|
||||
counted: one Saturn BIOS serves seven."""
|
||||
raw = value if isinstance(value, list) else [value] if value else []
|
||||
@@ -88,13 +88,13 @@ def _region_words(value: object, most: int = 0) -> str:
|
||||
words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw]
|
||||
if most and len(words) > most:
|
||||
words = words[:most] + [f"{len(words) - most} more"]
|
||||
return _said_as_list(words)
|
||||
return said_as_list(words)
|
||||
|
||||
|
||||
_CATEGORY_WORDS = {"bios": "BIOS", "game_data": "game data", "bios_zip": "BIOS ZIP"}
|
||||
|
||||
|
||||
def _snippet_noun(names: Iterable[str], firmware: int, fetched: int) -> str:
|
||||
def snippet_noun(names: Iterable[str], firmware: int, fetched: int) -> str:
|
||||
"""What an emulator's files are called in its snippet. A Switch
|
||||
emulator reads keys, and "eden keys" is what readers search for. Ship
|
||||
of Harkinian reads game ROMs, which are no BIOS."""
|
||||
@@ -142,7 +142,7 @@ def _status_badges(f: dict, in_repo: bool, for_system: str, shipped: bool) -> li
|
||||
return badges
|
||||
|
||||
|
||||
def _file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]:
|
||||
def file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]:
|
||||
"""The status chips shown beside a file name.
|
||||
|
||||
Fourteen independent optional fields, each contributing at most one
|
||||
@@ -176,7 +176,7 @@ def _file_badges(f: dict, in_repo: bool, for_system: str = "") -> list[str]:
|
||||
if region:
|
||||
# Labelled: "optional in repo japan" read as one run-on phrase.
|
||||
badges.append(
|
||||
f'<span class="rb-badge rb-badge-muted">Region: {_region_words(region)}</span>'
|
||||
f'<span class="rb-badge rb-badge-muted">Region: {region_words(region)}</span>'
|
||||
)
|
||||
if storage and storage != "embedded":
|
||||
badges.append(
|
||||
@@ -228,7 +228,7 @@ def _load_from_text(value: object) -> str:
|
||||
"""
|
||||
if value in (None, "", "system_dir"):
|
||||
return ""
|
||||
return _by_build(value, lambda v: _LOAD_FROM.get(v, _code(v)))
|
||||
return _by_build(value, lambda v: _LOAD_FROM.get(v, code_span(v)))
|
||||
|
||||
|
||||
def _found_by_text(value: object) -> str:
|
||||
@@ -238,7 +238,7 @@ def _found_by_text(value: object) -> str:
|
||||
"content": "content (the code scans the folder and identifies the file "
|
||||
"by its hash, any file name works)",
|
||||
}
|
||||
return _by_build(value, lambda v: words.get(v, _code(v)))
|
||||
return _by_build(value, lambda v: words.get(v, code_span(v)))
|
||||
|
||||
|
||||
def _on_mismatch_lines(value: object) -> list[str]:
|
||||
@@ -247,7 +247,7 @@ def _on_mismatch_lines(value: object) -> list[str]:
|
||||
if value == "warn":
|
||||
return [f"On a failed check: {said['warn']}"]
|
||||
if isinstance(value, dict):
|
||||
return [f"On a failed {check} check: {said.get(str(how), _code(str(how)))}"
|
||||
return [f"On a failed {check} check: {said.get(str(how), code_span(str(how)))}"
|
||||
for check, how in value.items()]
|
||||
return []
|
||||
|
||||
@@ -259,7 +259,7 @@ def emulator_setups(coverages: dict, profiles: dict) -> dict[str, list[str]]:
|
||||
for emulator in resolve_platform_cores(cov["config"], profiles):
|
||||
setups.setdefault(emulator, []).append(platform)
|
||||
return {
|
||||
emulator: sorted(names, key=lambda p: _platform_display(p).casefold())
|
||||
emulator: sorted(names, key=lambda p: platform_display(p).casefold())
|
||||
for emulator, names in setups.items()
|
||||
}
|
||||
|
||||
@@ -273,30 +273,30 @@ def _validation_names(validation: dict | list | None) -> set[str]:
|
||||
|
||||
def _exact_size(size: int) -> str:
|
||||
"""A rounded size with its bytes, where the bytes are not the same figure."""
|
||||
return _fmt_size(size) if size < 1024 else f"{_fmt_size(size)} ({size:,} bytes)"
|
||||
return fmt_size(size) if size < 1024 else f"{fmt_size(size)} ({size:,} bytes)"
|
||||
|
||||
|
||||
def _build_file_links(pin_build: list[dict]) -> list[str]:
|
||||
"""Each platform build file that holds the revision, linked at the
|
||||
commit it was read at when the source record holds it. The prose of
|
||||
pin_frozen named the file as plain text."""
|
||||
from sitegen.sources import _browse_repo, tree_holds
|
||||
from sitegen.sources import browse_repo, tree_holds
|
||||
|
||||
links = []
|
||||
for build in pin_build:
|
||||
repo = _browse_repo(str(build["repo"]))
|
||||
repo = browse_repo(str(build["repo"]))
|
||||
path = str(build["path"])
|
||||
revision = str(build["revision"])
|
||||
text = f"{_escape_tags(_platform_display(str(build['platform'])))} {_code(path)}"
|
||||
text = f"{escape_tags(platform_display(str(build['platform'])))} {code_span(path)}"
|
||||
# Linked where the record saw the file at that commit, as every
|
||||
# source link is: a tag can move, and is never recorded.
|
||||
if repo is not None and tree_holds(repo, revision, path):
|
||||
text = f"[{text}]({_source_permalink(repo, revision, path, None, None)})"
|
||||
links.append(f"{text} at {_code(str(build['revision']))} sets {_code(str(build['variable']))}")
|
||||
text = f"[{text}]({source_permalink(repo, revision, path, None, None)})"
|
||||
links.append(f"{text} at {code_span(str(build['revision']))} sets {code_span(str(build['variable']))}")
|
||||
return links
|
||||
|
||||
|
||||
def _build_rows(profile: dict) -> list[str]:
|
||||
def build_rows(profile: dict) -> list[str]:
|
||||
"""Meta card rows for who ships the build, how its files are found, why
|
||||
its revision is held and where its releases are announced."""
|
||||
rows = []
|
||||
@@ -314,7 +314,7 @@ def _build_rows(profile: dict) -> list[str]:
|
||||
("upstream_frozen", "Upstream revision held")):
|
||||
frozen = profile.get(field)
|
||||
if frozen:
|
||||
held = _escape_tags(' '.join(str(frozen).split())).replace('|', r'\|')
|
||||
held = escape_tags(' '.join(str(frozen).split())).replace('|', r'\|')
|
||||
rows.append(f"| {label} | {held} |")
|
||||
builds = _build_file_links(profile.get("pin_build") or [])
|
||||
if builds:
|
||||
@@ -324,21 +324,21 @@ def _build_rows(profile: dict) -> list[str]:
|
||||
url = str(announced["url"])
|
||||
row = f"| Releases announced at | [{url}]({url})"
|
||||
if announced.get("no_genuine_copy"):
|
||||
row += (f" (version {_escape_tags(str(announced['no_genuine_copy']))} "
|
||||
row += (f" (version {escape_tags(str(announced['no_genuine_copy']))} "
|
||||
"announced there, found only as rebuilt copies)")
|
||||
rows.append(row + " |")
|
||||
return rows
|
||||
|
||||
|
||||
def _entry_label(f: dict, profile: dict) -> str:
|
||||
def entry_label(f: dict, profile: dict) -> str:
|
||||
"""The name a file card goes by, its title without the badges."""
|
||||
fname = f.get("name", "")
|
||||
if f is any_name_bios(profile):
|
||||
# Found by content: the name is an example, any image of the system works.
|
||||
system = system_name((profile.get("systems") or [""])[0])
|
||||
return (f"a {system} BIOS (example: {_code(fname)})" if _named_example(str(fname))
|
||||
return (f"a {system} BIOS (example: {code_span(fname)})" if named_example(str(fname))
|
||||
else f"a {system} BIOS, any file name")
|
||||
return _code(fname)
|
||||
return code_span(fname)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -382,7 +382,7 @@ def _card_place_details(f: dict, profile: dict, owner: str, data_href: str) -> l
|
||||
if found:
|
||||
details.append(f"Found by: {found}")
|
||||
if fsystem:
|
||||
details.append(f"System: {_named_system_link(fsystem, '../')}")
|
||||
details.append(f"System: {named_system_link(fsystem, '../')}")
|
||||
return details
|
||||
|
||||
|
||||
@@ -393,7 +393,7 @@ def _card_size_details(f: dict) -> list[str]:
|
||||
fmax = f.get("max_size")
|
||||
# Where the code compares the size, the exact bytes: raze tells three
|
||||
# DUKE3D.GRP apart by size, all three shown as 42.3 MB.
|
||||
sized = _exact_size if "size" in _validation_names(f.get("validation", [])) else _fmt_size
|
||||
sized = _exact_size if "size" in _validation_names(f.get("validation", [])) else fmt_size
|
||||
bounds = []
|
||||
if fmin:
|
||||
bounds.append(f"min {sized(fmin)}")
|
||||
@@ -423,22 +423,22 @@ def _card_hash_details(f: dict) -> list[str]:
|
||||
# Starlight folds the hashes and gives each a copy button.
|
||||
copyable = markup.starlight()
|
||||
if fsha1:
|
||||
details.append(f"SHA1: {_hash_spans(fsha1, copyable)}")
|
||||
details.append(f"SHA1: {hash_spans(fsha1, copyable)}")
|
||||
if fmd5:
|
||||
details.append(f"MD5: {_hash_spans(fmd5, copyable)}")
|
||||
details.append(f"MD5: {hash_spans(fmd5, copyable)}")
|
||||
if fcrc32:
|
||||
crcs = fcrc32 if isinstance(fcrc32, list) else [fcrc32]
|
||||
details.append("CRC32: " + ", ".join(
|
||||
markup.hash_value(crc, True) if copyable else f"`{crc}`" for crc in crcs))
|
||||
if fsha256:
|
||||
details.append(f"SHA256: {_hash_spans(fsha256, copyable)}")
|
||||
details.append(f"SHA256: {hash_spans(fsha256, copyable)}")
|
||||
if fadler32:
|
||||
# Printed as the downloads spell a hash, one per code span: the list
|
||||
# repr read `['0x66f334fe', ...]`. Dolphin hashes its DSP ROMs over
|
||||
# byte-swapped 16-bit words, so the raw Adler-32 the downloads carry
|
||||
# for the same file differs, and the card says which one it lists.
|
||||
values = fadler32 if isinstance(fadler32, list) else [fadler32]
|
||||
shown = ", ".join(_code(str(v).lower().removeprefix("0x")) for v in values)
|
||||
shown = ", ".join(code_span(str(v).lower().removeprefix("0x")) for v in values)
|
||||
if f.get("adler32_byteswap"):
|
||||
details.append(
|
||||
f"Adler32 over the file's 16-bit words byte-swapped: {shown} "
|
||||
@@ -492,7 +492,7 @@ def _card_reading_details(f: dict, profile: dict) -> list[str]:
|
||||
# for the file.
|
||||
details.append(f"Asked for by: {asker}")
|
||||
details.append(
|
||||
f"Source: {_source_ref_markdown(profile, source_ref)}"
|
||||
f"Source: {source_ref_markdown(profile, source_ref)}"
|
||||
)
|
||||
return details
|
||||
|
||||
@@ -511,7 +511,7 @@ def _card_copy_line(
|
||||
# said "in repo" without naming the file.
|
||||
page = card_page(held, sha1)
|
||||
return [
|
||||
f"Collection copy: [{_code(held)}]"
|
||||
f"Collection copy: [{code_span(held)}]"
|
||||
f"(../systems/{urllib.parse.quote(page)}.md#sha1-{sha1[:12]})"
|
||||
]
|
||||
if in_repo and not any(d.startswith("Collection copies:") for d in details):
|
||||
@@ -536,13 +536,13 @@ def _card_copy_details(
|
||||
*entry_target(f, profile.get("files") or []), owner=owner)
|
||||
held = consumers.path_of(sha1) if sha1 and in_repo else ""
|
||||
added.extend(_card_copy_line(f, consumers, held, sha1, in_repo, details + added))
|
||||
plat_links = _platform_links(sha1, consumers) if sha1 else []
|
||||
plat_links = platform_links(sha1, consumers) if sha1 else []
|
||||
if plat_links and markup.starlight():
|
||||
# Grouped by where the setups put the file, as the system card
|
||||
# says it: twelve setups repeating scph5502.bin took twelve
|
||||
# names and twelve paths where a few say it. One sentence a
|
||||
# place: a list or a line break was one more element a place.
|
||||
places = _places_markdown(_platform_places(sha1, consumers))
|
||||
places = places_markdown(platform_places(sha1, consumers))
|
||||
added.append("Platforms: " + ". ".join(places))
|
||||
elif plat_links:
|
||||
added.append(f"Platforms: {', '.join(plat_links)}")
|
||||
@@ -584,21 +584,21 @@ def _card_heading(f: dict, profile: dict, in_repo: bool, anchor: str, layout: Ca
|
||||
# above the DS files, for an emulator most people run for DS games.
|
||||
for_system = (system_name(str(fsystem))
|
||||
if fsystem and len(profile.get("systems") or []) > 1 else "")
|
||||
badges = _file_badges(f, in_repo, for_system)
|
||||
badges = file_badges(f, in_repo, for_system)
|
||||
badge_str = " ".join(badges)
|
||||
lines.append(markup.block_open("div", 'class="rb-file-entry"'))
|
||||
lines.append("")
|
||||
marker = f'<span id="{layout.alias}"></span>' if layout.alias else ""
|
||||
label = _entry_label(f, profile)
|
||||
label = entry_label(f, profile)
|
||||
title = f"{marker}{label}" if layout.badges_apart else f"{marker}{label} {badge_str}"
|
||||
lines.append(_card_title(title, anchor, weight=5))
|
||||
lines.append(card_title(title, anchor, weight=5))
|
||||
lines.append("")
|
||||
if desc:
|
||||
lines.extend([data_root_words(_escape_tags(str(desc)), layout.data_href), ""])
|
||||
lines.extend([data_root_words(escape_tags(str(desc)), layout.data_href), ""])
|
||||
return lines
|
||||
|
||||
|
||||
def _render_emulator_file(
|
||||
def render_emulator_file(
|
||||
f: dict,
|
||||
profile: dict,
|
||||
consumers: FileConsumers | None,
|
||||
@@ -639,11 +639,11 @@ def _render_emulator_file(
|
||||
return lines
|
||||
lines.extend(f"- {d}" for d in details)
|
||||
if fnote:
|
||||
lines.append(f"- {data_root_words(_escape_tags(link_prose_citations(profile, str(fnote))), data_href)}")
|
||||
lines.append(f"- {data_root_words(escape_tags(link_prose_citations(profile, str(fnote))), data_href)}")
|
||||
if not in_repo and f.get("unsourceable"):
|
||||
lines.append(f"- {_unsourceable_line(f)}")
|
||||
lines.extend(_contents_lines(contents))
|
||||
lines[body_start:] = _search_skipped_apart(lines[body_start:])
|
||||
lines[body_start:] = search_skipped_apart(lines[body_start:])
|
||||
lines.append("")
|
||||
lines.append("</div>")
|
||||
lines.append("")
|
||||
@@ -661,9 +661,9 @@ def _contents_lines(contents: list) -> list[str]:
|
||||
if isinstance(c, dict):
|
||||
parts = []
|
||||
if c.get("description"):
|
||||
parts.append(_escape_tags(str(c["description"])))
|
||||
parts.append(escape_tags(str(c["description"])))
|
||||
if c.get("size"):
|
||||
parts.append(_fmt_size(c["size"]))
|
||||
parts.append(fmt_size(c["size"]))
|
||||
if c.get("crc32"):
|
||||
parts.append(f"CRC32 `{c['crc32']}`")
|
||||
if c.get("sha1"):
|
||||
@@ -751,7 +751,7 @@ def _emulator_card_folds(
|
||||
open_lines = [d for d in key if not skipped(d)]
|
||||
if fnote:
|
||||
open_lines.append(data_root_words(
|
||||
_escape_tags(link_prose_citations(profile, str(fnote))), data_href))
|
||||
escape_tags(link_prose_citations(profile, str(fnote))), data_href))
|
||||
if not in_repo and f.get("unsourceable"):
|
||||
open_lines.append(_unsourceable_line(f))
|
||||
lines = [f"- {d}" for d in open_lines]
|
||||
@@ -768,12 +768,12 @@ def _emulator_card_folds(
|
||||
tuple(f"- {h}" for h in _ENTRY_HASHES))])
|
||||
words = words if len(words) <= 3 else [*words[:3], "more"]
|
||||
if members:
|
||||
words.append(_count(len(members), "member"))
|
||||
words.append(count_text(len(members), "member"))
|
||||
hidden_part = [*shut_fold, "", *members] if members else shut_fold
|
||||
body = (hidden_part if not read_fold else [
|
||||
"", markup.block_open("div", f'class="rb-search-skip" {markup.search_exclude()}'),
|
||||
"", *hidden_part, "", "</div>", "", *read_fold])
|
||||
fold = card_fold(_listed_words(words), body, skip=False)
|
||||
fold = card_fold(listed_words(words), body, skip=False)
|
||||
# A fold the search skips whole sits in the skipped block before it, with
|
||||
# no attribute of its own: on a page of 200 MAME cards the attribute, the
|
||||
# class and a block each were 12 KB.
|
||||
@@ -793,25 +793,25 @@ def _held_copy_line(copy: tuple[str, str], consumers: FileConsumers) -> str:
|
||||
path, member = copy
|
||||
parts = path.rstrip("/").split("/")
|
||||
if member:
|
||||
archive = _code(path)
|
||||
archive = code_span(path)
|
||||
zsha1 = consumers.sha1_at(path)
|
||||
if zsha1 and len(parts) >= 3 and parts[0] == "bios":
|
||||
page = urllib.parse.quote(card_page(path, zsha1))
|
||||
archive = f"[{archive}](../systems/{page}.md#sha1-{zsha1[:12]})"
|
||||
return f"Collection copy: member {_code(member)} of {archive}"
|
||||
return f"Collection copy: member {code_span(member)} of {archive}"
|
||||
if parts[0] == "data" and len(parts) >= 2:
|
||||
ref, inside = parts[1], "/".join(parts[2:])
|
||||
if path.endswith("/"):
|
||||
where = _code(inside + "/") if inside else "the tree"
|
||||
return f"Collection copy: {where} in the {_code(ref)} data directory"
|
||||
info = (_DATA_MEMBERS.get(ref) or {}).get(inside) or {}
|
||||
shown = _code(inside)
|
||||
where = code_span(inside + "/") if inside else "the tree"
|
||||
return f"Collection copy: {where} in the {code_span(ref)} data directory"
|
||||
info = (DATA_MEMBERS.get(ref) or {}).get(inside) or {}
|
||||
shown = code_span(inside)
|
||||
if info.get("sha1"):
|
||||
shown = (f'<a href="../../files/?sha1={info["sha1"]}">'
|
||||
f"<code>{html.escape(inside)}</code></a>")
|
||||
return f"Collection copy: {shown} in the {_code(ref)} data directory"
|
||||
return f"Collection copy: {shown} in the {code_span(ref)} data directory"
|
||||
tree = f"{REPO_URL}/tree/main/{urllib.parse.quote(path.rstrip('/'))}"
|
||||
return f"Collection copy: [{_code(path)}]({tree})"
|
||||
return f"Collection copy: [{code_span(path)}]({tree})"
|
||||
|
||||
|
||||
def _directory_copies(entry: dict, consumers: FileConsumers) -> list[str]:
|
||||
@@ -826,11 +826,11 @@ def _directory_copies(entry: dict, consumers: FileConsumers) -> list[str]:
|
||||
return []
|
||||
folder = os.path.commonpath(held) if len(held) > 1 else os.path.dirname(held[0])
|
||||
parts = folder.split("/")
|
||||
where = _code(folder + "/")
|
||||
where = code_span(folder + "/")
|
||||
if len(parts) >= 3 and parts[0] == "bios":
|
||||
where = f"[{where}]({console_href(_slug(parts[1]), parts[2], '../')})"
|
||||
where = f"[{where}]({console_href(manufacturer_slug(parts[1]), parts[2], '../')})"
|
||||
tree = f"{REPO_URL}/tree/main/{urllib.parse.quote(folder)}"
|
||||
return [f"Collection copies: {_count(len(members), 'file')} under {where} "
|
||||
return [f"Collection copies: {count_text(len(members), 'file')} under {where} "
|
||||
f"([browse]({tree}))"]
|
||||
|
||||
|
||||
@@ -874,7 +874,7 @@ def _version_said(value: object, basis: dict, profile: dict, mode: str = "") ->
|
||||
url = version_basis_url(profile, basis, mode) if kind in ("file", "tag") else ""
|
||||
|
||||
def shown(text: object) -> str:
|
||||
return f"[{_code(str(text))}]({url})" if url else _code(str(text))
|
||||
return f"[{code_span(str(text))}]({url})" if url else code_span(str(text))
|
||||
|
||||
if kind == "file":
|
||||
return f"{value}, stated in {shown(basis.get('path'))}"
|
||||
@@ -999,7 +999,7 @@ def with_archive_counts(page: str, counts: dict[str, int]) -> str:
|
||||
return _ARCHIVE_BLOCK.sub(lambda m: f"{m.group(1)}{block}{m.group(3)}", page, count=1)
|
||||
|
||||
|
||||
def _render_metadata_rows(profile: dict) -> list[str]:
|
||||
def render_metadata_rows(profile: dict) -> list[str]:
|
||||
"""Scalar profile fields, one table row each.
|
||||
|
||||
Anything structured belongs in a collapsible block below, not in a
|
||||
@@ -1034,9 +1034,9 @@ def _render_metadata_rows(profile: dict) -> list[str]:
|
||||
and not str(val).startswith(("/", "~", "$")) and ":" not in str(val):
|
||||
# A bare `bios/` read as a place on the device: it is a folder
|
||||
# inside the app's own data folder, which the notes describe.
|
||||
lines.append(f"| {label} | {_code(val)}, inside the app's own data folder |")
|
||||
lines.append(f"| {label} | {code_span(val)}, inside the app's own data folder |")
|
||||
elif field == "bios_size" and isinstance(val, int):
|
||||
lines.append(f"| {label} | {_fmt_size(val)} ({val:,} bytes) |")
|
||||
lines.append(f"| {label} | {fmt_size(val)} ({val:,} bytes) |")
|
||||
elif isinstance(val, str) and val.startswith("http"):
|
||||
lines.append(f"| {label} | [{val}]({val}) |")
|
||||
else:
|
||||
@@ -1047,17 +1047,17 @@ def _render_metadata_rows(profile: dict) -> list[str]:
|
||||
for key in ("windows", "macos", "linux", "android", "ios"):
|
||||
root = roots.get(key)
|
||||
if isinstance(root, dict) and root.get("path"):
|
||||
lines.append(f"| Data folder ({_OS_LABELS[key]}) | "
|
||||
f"{_under_root(str(root['path']), '')} |")
|
||||
lines.append(f"| Data folder ({OS_LABELS[key]}) | "
|
||||
f"{under_root(str(root['path']), '')} |")
|
||||
if profile.get("source_ref"):
|
||||
lines.append(
|
||||
f"| Source ref | {_source_ref_markdown(profile, profile['source_ref'])} |"
|
||||
f"| Source ref | {source_ref_markdown(profile, profile['source_ref'])} |"
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
# Data directory members and revisions, read once per build.
|
||||
_DATA_MEMBERS: dict[str, dict[str, dict]] = {}
|
||||
DATA_MEMBERS: dict[str, dict[str, dict]] = {}
|
||||
|
||||
|
||||
def any_name_bios(profile: dict) -> dict | None:
|
||||
@@ -1080,7 +1080,7 @@ def any_name_bios(profile: dict) -> dict | None:
|
||||
return required[0]
|
||||
|
||||
|
||||
def _named_example(name: str) -> bool:
|
||||
def named_example(name: str) -> bool:
|
||||
"""A real file name, not a placeholder such as `<bios>.bin`."""
|
||||
return bool(name) and "<" not in name
|
||||
|
||||
@@ -1091,5 +1091,5 @@ def _unsourceable_line(f: dict) -> str:
|
||||
same-named file from being served in its place: the file is still
|
||||
wanted, and "Not collectable" sent readers away from KANJI2.ROM, which
|
||||
MAME's fm7740sx.zip carries."""
|
||||
return (f"Not collected yet: {_escape_tags(str(f['unsourceable']))} "
|
||||
return (f"Not collected yet: {escape_tags(str(f['unsourceable']))} "
|
||||
"([files not collected yet](../gaps.md#not-collected-yet))")
|
||||
@@ -12,30 +12,30 @@ from model.systemnames import system_name
|
||||
from packs.crossref import FileConsumers
|
||||
from sitegen import entries as siteentries, markup, measurements as sitemeasurements
|
||||
from sitegen.cards import ROMSET_FAQ, emulator_file_anchors
|
||||
from sitegen.config import REPO_URL, _date_line, yaml
|
||||
from sitegen.config import REPO_URL, date_line, yaml
|
||||
from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT
|
||||
from sitegen.descriptions import _said_as_list
|
||||
from sitegen.descriptions import said_as_list
|
||||
from sitegen.emulatorcards import (
|
||||
CardLayout,
|
||||
_DATA_MEMBERS,
|
||||
_build_rows,
|
||||
_entry_label,
|
||||
_file_badges,
|
||||
_named_example,
|
||||
_named_system_link,
|
||||
_region_words,
|
||||
_render_emulator_file,
|
||||
_render_metadata_rows,
|
||||
DATA_MEMBERS,
|
||||
build_rows,
|
||||
entry_label,
|
||||
file_badges,
|
||||
named_example,
|
||||
named_system_link,
|
||||
region_words,
|
||||
render_emulator_file,
|
||||
render_metadata_rows,
|
||||
any_name_bios,
|
||||
emulator_romset,
|
||||
version_markdown,
|
||||
)
|
||||
from sitegen.emulatorsindex import CLS_LABEL_ONE
|
||||
from sitegen.fields import _render_platform_details, _render_structured_blocks, search_excluded
|
||||
from sitegen.home import _next_block
|
||||
from sitegen.fields import render_platform_details, render_structured_blocks, search_excluded
|
||||
from sitegen.home import next_block
|
||||
from sitegen.install import (
|
||||
_install_block,
|
||||
_platform_display,
|
||||
install_block,
|
||||
platform_display,
|
||||
comes_with_app,
|
||||
data_folder_block,
|
||||
data_root_words,
|
||||
@@ -43,16 +43,16 @@ from sitegen.install import (
|
||||
)
|
||||
from sitegen.lookup import data_directory_origin, data_tree_pages
|
||||
from sitegen.render import (
|
||||
_admonition_body,
|
||||
_code,
|
||||
_count,
|
||||
_escape_tags,
|
||||
_fmt_size,
|
||||
admonition_body,
|
||||
code_span,
|
||||
count_text,
|
||||
escape_tags,
|
||||
fmt_size,
|
||||
card_page,
|
||||
record_emulator_cards,
|
||||
)
|
||||
from sitegen.sources import _source_ref_markdown, link_prose_citations, revision_markdown
|
||||
from sitegen.startwith import _parts
|
||||
from sitegen.sources import source_ref_markdown, link_prose_citations, revision_markdown
|
||||
from sitegen.startwith import card_runs
|
||||
from sitegen.structured import emulator_file_aliases
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ def _distinct_spellings(names: list) -> list[str]:
|
||||
return list(seen.values())
|
||||
|
||||
|
||||
def _availability_check(
|
||||
def availability_check(
|
||||
db: dict, data_names: set[str] | None, owner: str = "",
|
||||
) -> Callable[[dict], bool]:
|
||||
"""A predicate answering whether the collection holds a file.
|
||||
@@ -156,7 +156,7 @@ def _regional_set(requirements: list[list[dict]]) -> list[dict]:
|
||||
members = requirements[0]
|
||||
if not all(f.get("region") for f in members):
|
||||
return []
|
||||
return members if len({_region_words(f["region"]) for f in members}) >= 2 else []
|
||||
return members if len({region_words(f["region"]) for f in members}) >= 2 else []
|
||||
|
||||
|
||||
def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> list[str]:
|
||||
@@ -180,7 +180,7 @@ def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> lis
|
||||
|
||||
# Sentences, one number format: the line read "1,563 files | 164
|
||||
# required, 1399 optional | 1563 in repo".
|
||||
total = f"**{_count(len(slots), 'file')}**"
|
||||
total = f"**{count_text(len(slots), 'file')}**"
|
||||
if sum(len(group) for group in slots) != len(slots):
|
||||
total += f" ({sum(len(group) for group in slots):,} accepted versions)"
|
||||
line = f"{total}: {req_count:,} required, {optional:,} optional."
|
||||
@@ -198,7 +198,7 @@ def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> lis
|
||||
if hle_count:
|
||||
line += f" {hle_count:,} {'has' if hle_count == 1 else 'have'} an HLE fallback."
|
||||
if shipped:
|
||||
line += f" {_count(shipped, 'more file')} {'comes' if shipped == 1 else 'come'} with the app."
|
||||
line += f" {count_text(shipped, 'more file')} {'comes' if shipped == 1 else 'come'} with the app."
|
||||
lines = [line, ""]
|
||||
|
||||
categories = [f.get("category", "bios") for f in files]
|
||||
@@ -210,7 +210,7 @@ def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> lis
|
||||
)
|
||||
if categories.count(key)
|
||||
]
|
||||
lines.extend([f"By kind: {_said_as_list(cats)}.", ""])
|
||||
lines.extend([f"By kind: {said_as_list(cats)}.", ""])
|
||||
return lines
|
||||
|
||||
|
||||
@@ -228,16 +228,16 @@ def _emulator_held_line(files: list[dict], available: Callable[[dict], bool]) ->
|
||||
held = [f"{in_repo:,} in repo", f"{len(slots) - in_repo - unsourceable:,} missing"]
|
||||
if unsourceable:
|
||||
held.append(f"{unsourceable:,} unsourceable")
|
||||
return [f"<p><small>In this collection: {_said_as_list(held)}.</small></p>", ""]
|
||||
return [f"<p><small>In this collection: {said_as_list(held)}.</small></p>", ""]
|
||||
|
||||
|
||||
_DATA_REVISIONS: dict[str, dict] = {}
|
||||
DATA_REVISIONS: dict[str, dict] = {}
|
||||
# Emulator -> the platforms that run it, as resolve_platform_cores answers.
|
||||
_EMULATOR_SETUPS: dict[str, list[str]] = {}
|
||||
EMULATOR_SETUPS: dict[str, list[str]] = {}
|
||||
# The measurement index items of each emulator, for the proof lines of its page.
|
||||
_MEASUREMENT_ITEMS: dict[str, list[dict]] = {}
|
||||
MEASUREMENT_ITEMS: dict[str, list[dict]] = {}
|
||||
# The emulator pages that list each data directory, by ref.
|
||||
_DATA_READERS: dict[str, list[tuple[str, str]]] = {}
|
||||
DATA_READERS: dict[str, list[tuple[str, str]]] = {}
|
||||
|
||||
|
||||
def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[str]) -> list[str]:
|
||||
@@ -252,7 +252,7 @@ def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[
|
||||
anchor = f"sha1-{sha1[:12]}"
|
||||
span = "" if anchor in anchors else f'<span id="{anchor}"></span>'
|
||||
anchors.add(anchor)
|
||||
table.append(f"| {span}{_code(member)} | {_fmt_size(int(info.get('size', 0)))} | {_code(sha1)} |")
|
||||
table.append(f"| {span}{code_span(member)} | {fmt_size(int(info.get('size', 0)))} | {code_span(sha1)} |")
|
||||
return table
|
||||
|
||||
|
||||
@@ -260,16 +260,16 @@ def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]],
|
||||
index: int) -> str:
|
||||
"""One page of a large data directory's file list."""
|
||||
stem, names = pages[index]
|
||||
members = _DATA_MEMBERS.get(ref) or {}
|
||||
members = DATA_MEMBERS.get(ref) or {}
|
||||
part = f" (part {index + 1} of {len(pages)})" if len(pages) > 1 else ""
|
||||
read_by = _said_as_list([f"[{_escape_tags(display)}]({key}.md#data-directories)"
|
||||
for key, display in _DATA_READERS.get(ref, [])])
|
||||
read_by = said_as_list([f"[{escape_tags(display)}]({key}.md#data-directories)"
|
||||
for key, display in DATA_READERS.get(ref, [])])
|
||||
# A file list out of the search: "dolphin" found three parts of the
|
||||
# dolphin-sys tree, on their title, before the Dolphin page.
|
||||
front: dict = {"level": "reference", "search": "exclude"}
|
||||
# The reader the tree is named after (dolphin for dolphin-sys), else
|
||||
# the first by name.
|
||||
readers = _DATA_READERS.get(ref) or []
|
||||
readers = DATA_READERS.get(ref) or []
|
||||
owner = max(readers, default=None,
|
||||
key=lambda reader: len(reader[0]) if ref.startswith(f"{reader[0]}-") else 0)
|
||||
if owner:
|
||||
@@ -284,14 +284,14 @@ def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]],
|
||||
*head,
|
||||
f"# The {ref} data directory{part}", "",
|
||||
f"{entry.get('description') or 'A data directory'}: "
|
||||
f"{_count(len(members), 'file')}, as the packs ship them."
|
||||
f"{count_text(len(members), 'file')}, as the packs ship them."
|
||||
+ (f" Read by {read_by}." if read_by else ""), "",
|
||||
]
|
||||
if len(pages) > 1:
|
||||
lines.extend([", ".join(f"[part {i}]({other}.md)" if other != stem else f"part {i}"
|
||||
for i, (other, _names) in enumerate(pages, 1)), ""])
|
||||
lines.extend(search_excluded(_data_member_table(members, names, set())))
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
@@ -353,7 +353,7 @@ def _entry_row_words(files: list[dict], profile: dict,
|
||||
for f, row in zip(files, cells):
|
||||
filled.setdefault(_card_section(f), set()).update(
|
||||
column for column, cell in enumerate(row) if cell)
|
||||
return [_html_words(_entry_label(f, profile)) + sum(
|
||||
return [_html_words(entry_label(f, profile)) + sum(
|
||||
_html_words(cell) or column in filled[_card_section(f)]
|
||||
for column, cell in enumerate(row))
|
||||
for f, row in zip(files, cells)]
|
||||
@@ -375,15 +375,15 @@ def emulator_parts(name: str, files: list, profile: dict | None = None,
|
||||
words = _entry_row_words(files, profile, available or (lambda _f: True))
|
||||
sizes = [words[i] for i in order]
|
||||
ceiling = max(EMULATOR_PART_WORDS, max(sizes))
|
||||
count = max(len(_parts(order, ceiling, sizes)), -(-len(files) // EMULATOR_CARDS_PER_PART))
|
||||
count = max(len(card_runs(order, ceiling, sizes)), -(-len(files) // EMULATOR_CARDS_PER_PART))
|
||||
while True:
|
||||
# The fewest words a part can hold for the parts to be ``count``:
|
||||
# cut at the ceiling, the last part took what the others left.
|
||||
share = min(-(-sum(sizes) // count), ceiling)
|
||||
runs = _parts(order, share, sizes)
|
||||
runs = card_runs(order, share, sizes)
|
||||
while len(runs) > count:
|
||||
share = min(share + max(1, share // 50), ceiling)
|
||||
runs = _parts(order, share, sizes)
|
||||
runs = card_runs(order, share, sizes)
|
||||
if max(len(run) for run in runs) <= EMULATOR_CARDS_PER_PART:
|
||||
return [(f"{name}-files-{index}", run) for index, run in enumerate(runs, 1)]
|
||||
count += 1
|
||||
@@ -396,7 +396,7 @@ def emulator_parts(name: str, files: list, profile: dict | None = None,
|
||||
# "7 files" block. A split emulator's card pages always use the table.
|
||||
EMULATOR_TABLE_MIN = 6
|
||||
ENTRY_HEADS = ["File", "Contents", "Status", "Hash"]
|
||||
# The end of the badge _file_badges writes for an entry of each section.
|
||||
# The end of the badge file_badges writes for an entry of each section.
|
||||
_SECTION_BADGE = {"required": ">required</span>", "optional": ">optional</span>",
|
||||
"with_app": ">comes with the app</span>"}
|
||||
|
||||
@@ -418,7 +418,7 @@ def _entry_cells(f: dict, profile: dict, available: Callable[[dict], bool]) -> l
|
||||
many = len(profile.get("systems") or []) > 1
|
||||
for_system = system_name(str(f["system"])) if f.get("system") and many else ""
|
||||
contents = f.get("contents") or []
|
||||
badges = _file_badges(f, available(f), for_system)
|
||||
badges = file_badges(f, available(f), for_system)
|
||||
# The first badge says whether the entry is needed: under Required,
|
||||
# Optional or Comes with the app it repeats the section heading.
|
||||
# One element and two words fewer on each of MAME's 1,563 rows.
|
||||
@@ -481,7 +481,7 @@ def _summary_table(files: list[dict], indexes: list[int], cell: Callable[[int, s
|
||||
if needed == "yes" and multi_system and f.get("system"):
|
||||
needed = f"for {system_name(str(f['system']))}"
|
||||
rows.append((cell(i, str(f.get("path") or f.get("name", ""))),
|
||||
_region_words(f.get("region"), 3), needed, _hash_short(f)))
|
||||
region_words(f.get("region"), 3), needed, _hash_short(f)))
|
||||
keep = [0] + [column for column in (1, 3) if any(row[column] for row in rows)]
|
||||
if len({row[2] for row in rows}) > 1:
|
||||
keep.append(2)
|
||||
@@ -549,8 +549,8 @@ def _any_name_folder(profile: dict, entry: dict) -> str:
|
||||
# A bare `bios/` is a folder inside the app's own data folder.
|
||||
own = ("[the app's data folder](#data-folder)" if profile.get("data_root")
|
||||
else "the app's own data folder")
|
||||
return f"the {_code(folder.strip('/'))} folder inside {own}"
|
||||
return f"{_code(folder)}, inside the BIOS folder"
|
||||
return f"the {code_span(folder.strip('/'))} folder inside {own}"
|
||||
return f"{code_span(folder)}, inside the BIOS folder"
|
||||
|
||||
|
||||
def _any_name_steps(emu_name: str, profile: dict, entry: dict, href: str,
|
||||
@@ -564,10 +564,10 @@ def _any_name_steps(emu_name: str, profile: dict, entry: dict, href: str,
|
||||
"""
|
||||
system = system_name((profile.get("systems") or [""])[0])
|
||||
example = str(entry.get("name") or "")
|
||||
if _named_example(example) and href:
|
||||
get = f"Download [{_code(example)}]({href})."
|
||||
if named_example(example) and href:
|
||||
get = f"Download [{code_span(example)}]({href})."
|
||||
else:
|
||||
get = f"Get one from the {_named_system_link(profile['systems'][0], '../')} files."
|
||||
get = f"Get one from the {named_system_link(profile['systems'][0], '../')} files."
|
||||
steps = [get]
|
||||
folders: list[str] = []
|
||||
if profile.get("type") == "standalone" and standalone_place(name, profile, entry):
|
||||
@@ -630,7 +630,7 @@ def _emulator_intro(emu_name: str, profile: dict, href: str = "", name: str = ""
|
||||
sentences = []
|
||||
if names:
|
||||
shown = names if len(names) <= 4 else names[:3] + [f"{len(names) - 3} more systems"]
|
||||
sentences.append(f"{emu_name} emulates {_said_as_list(shown)}.")
|
||||
sentences.append(f"{emu_name} emulates {said_as_list(shown)}.")
|
||||
regional = _regional_set(requirements)
|
||||
by_region = "" if regional else _regional_choice(required)
|
||||
others = len(files) - len(required)
|
||||
@@ -642,20 +642,20 @@ def _emulator_intro(emu_name: str, profile: dict, href: str = "", name: str = ""
|
||||
f"It needs one BIOS for the game's region, among the {len(regional):,} it accepts.")
|
||||
if others:
|
||||
sentences.append(
|
||||
f"The {_count(others, 'other file')} {'is' if others == 1 else 'are'} optional.")
|
||||
f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.")
|
||||
elif by_region:
|
||||
# Three required BIOS of three regions: the page said "3 of them
|
||||
# required" and read as "get all of these".
|
||||
sentences.append(f"It picks the BIOS for the game's region: {by_region}.")
|
||||
if others:
|
||||
sentences.append(
|
||||
f"The {_count(others, 'other file')} {'is' if others == 1 else 'are'} optional.")
|
||||
f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.")
|
||||
elif files:
|
||||
sentences.append(
|
||||
f"It reads {_count(len(files), 'file')}, {len(requirements):,} of them required: "
|
||||
f"It reads {count_text(len(files), 'file')}, {len(requirements):,} of them required: "
|
||||
"without a required file it does not start games."
|
||||
if requirements else
|
||||
f"It reads {_count(len(files), 'file')}, none of them required: it starts "
|
||||
f"It reads {count_text(len(files), 'file')}, none of them required: it starts "
|
||||
"games without them."
|
||||
)
|
||||
if any(len(members) > 1 for members in requirements):
|
||||
@@ -679,9 +679,9 @@ def _regional_choice(required: list[dict], most: int = 6) -> str:
|
||||
"""
|
||||
if not required or len(required) > most or not all(f.get("region") for f in required):
|
||||
return ""
|
||||
if len({_region_words(f["region"]) for f in required}) < 2:
|
||||
if len({region_words(f["region"]) for f in required}) < 2:
|
||||
return ""
|
||||
choices = [f"{f.get('name', '')} ({_region_words(f['region'], 3)})" for f in required]
|
||||
choices = [f"{f.get('name', '')} ({region_words(f['region'], 3)})" for f in required]
|
||||
return ", ".join(choices[:-1]) + f" or {choices[-1]}"
|
||||
|
||||
|
||||
@@ -729,7 +729,7 @@ def _source_rows(profile: dict) -> list[str]:
|
||||
if gone:
|
||||
# The links above answer 451 or reach a domain someone else now
|
||||
# owns: said beside them, with the date the profile observed it.
|
||||
rows.append(f"| Source status | gone: {_escape_tags(str(gone))} |")
|
||||
rows.append(f"| Source status | gone: {escape_tags(str(gone))} |")
|
||||
mirror = profile.get("source_mirror")
|
||||
if mirror:
|
||||
rows.append(f"| Mirror | [{mirror}]({mirror}) |" if str(mirror).startswith("http")
|
||||
@@ -749,8 +749,8 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]:
|
||||
revision = revision_markdown(profile)
|
||||
if revision:
|
||||
rows.append(f"| Revision | {revision} |")
|
||||
rows.extend(_build_rows(profile))
|
||||
setups = _EMULATOR_SETUPS.get(name)
|
||||
rows.extend(build_rows(profile))
|
||||
setups = EMULATOR_SETUPS.get(name)
|
||||
if setups:
|
||||
# The file cards name the setups whose own list holds a file: the
|
||||
# ones that run the emulator and pack its files were said nowhere.
|
||||
@@ -758,7 +758,7 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]:
|
||||
# other pages over their element budget. Out of the search: setup
|
||||
# names on 530 pages ranked the data page first for "batocera folder".
|
||||
rows.append(f"| Run by | <span {markup.search_exclude()}>" + ", ".join(
|
||||
f"[{_platform_display(p)}](../platforms/{p}.md)" for p in setups) + "</span> |")
|
||||
f"[{platform_display(p)}](../platforms/{p}.md)" for p in setups) + "</span> |")
|
||||
rows.append(f"| Profiled | {profile.get('profiled_date', 'unknown')} |")
|
||||
# The YAML is the reusable document this site renders, and the JSON is the
|
||||
# same profile for a program.
|
||||
@@ -771,7 +771,7 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]:
|
||||
rows.append(f"| Cores | {', '.join(_distinct_spellings(cores))} |")
|
||||
systems = profile.get("systems", [])
|
||||
if systems:
|
||||
sys_links = list(dict.fromkeys(_named_system_link(s, "../") for s in systems))
|
||||
sys_links = list(dict.fromkeys(named_system_link(s, "../") for s in systems))
|
||||
rows.append(f"| Systems | {', '.join(sys_links)} |")
|
||||
author = profile.get("author", "")
|
||||
if author:
|
||||
@@ -779,7 +779,7 @@ def _emulator_meta_rows(name: str, profile: dict) -> list[str]:
|
||||
based_on = profile.get("based_on", "")
|
||||
if based_on:
|
||||
rows.append(f"| Based on | {based_on} |")
|
||||
rows.extend(_render_metadata_rows(profile))
|
||||
rows.extend(render_metadata_rows(profile))
|
||||
return rows
|
||||
|
||||
|
||||
@@ -801,7 +801,7 @@ def _emulator_files_section(
|
||||
consumers = sources.consumers
|
||||
part_pages: dict[str, str] = {}
|
||||
lines: list[str] = []
|
||||
_file_available = _availability_check(sources.db, sources.data_names, name)
|
||||
_file_available = availability_check(sources.db, sources.data_names, name)
|
||||
|
||||
lines.extend(["## Files", ""])
|
||||
lines.extend(_emulator_file_summary(files, profile.get("groups")))
|
||||
@@ -813,7 +813,7 @@ def _emulator_files_section(
|
||||
data_href = f"{name}.md#data-folder" if parts else "#data-folder"
|
||||
table_form = markup.starlight() and (bool(parts) or len(files) >= EMULATOR_TABLE_MIN)
|
||||
cards = [
|
||||
_render_emulator_file(f, profile, consumers, files, _file_available, anchor, name,
|
||||
render_emulator_file(f, profile, consumers, files, _file_available, anchor, name,
|
||||
CardLayout(alias, data_href, badges_apart=table_form))
|
||||
for f, anchor, alias in zip(files, anchors, aliases)
|
||||
]
|
||||
@@ -855,27 +855,27 @@ def _data_directory_lines(
|
||||
line += f": {entry['description']}"
|
||||
lines.append(line)
|
||||
lines.extend(f" - {line}" for line in data_directory_origin(
|
||||
entry, _DATA_REVISIONS.get(ref) or {}))
|
||||
entry, DATA_REVISIONS.get(ref) or {}))
|
||||
if dd.get("mode"):
|
||||
lines.append(f" - Read by the {dd['mode']} build only")
|
||||
if dd.get("bundled"):
|
||||
lines.append(" - Installed with the emulator, so packs leave it out")
|
||||
if dd.get("source_ref"):
|
||||
lines.append(f" - Source: {_source_ref_markdown(profile, dd['source_ref'])}")
|
||||
members = _DATA_MEMBERS.get(ref) or {}
|
||||
lines.append(f" - Source: {source_ref_markdown(profile, dd['source_ref'])}")
|
||||
members = DATA_MEMBERS.get(ref) or {}
|
||||
tree_pages = data_tree_pages(ref, members)
|
||||
if tree_pages:
|
||||
where = (f"[a page of their own]({tree_pages[0][0]}.md)" if len(tree_pages) == 1
|
||||
else "pages of their own: " + ", ".join(
|
||||
f"[part {i}]({stem}.md)" for i, (stem, _names) in enumerate(tree_pages, 1)))
|
||||
lines.append(f" - {_count(len(members), 'file')}, listed on {where}")
|
||||
lines.append(f" - {count_text(len(members), 'file')}, listed on {where}")
|
||||
for index, (stem, _names) in enumerate(tree_pages):
|
||||
part_pages[stem] = _data_tree_page(ref, entry, tree_pages, index)
|
||||
elif members:
|
||||
table = _data_member_table(members, sorted(members), member_anchors)
|
||||
lines.append("")
|
||||
lines.extend(markup.details(
|
||||
"info", f"{_count(len(members), 'file')}, as the packs ship them",
|
||||
"info", f"{count_text(len(members), 'file')}, as the packs ship them",
|
||||
table, indent=" "))
|
||||
return lines, part_pages
|
||||
|
||||
@@ -957,12 +957,12 @@ def emulator_pages(
|
||||
# card took two screens above the files.
|
||||
lines.extend(markup.details("note", "About this profile", card))
|
||||
|
||||
lines.extend(_install_block(name, profile))
|
||||
lines.extend(install_block(name, profile))
|
||||
|
||||
lines.extend(_render_platform_details(profile))
|
||||
lines.extend(render_platform_details(profile))
|
||||
|
||||
if notes:
|
||||
body = _admonition_body(data_root_words(link_prose_citations(profile, notes))
|
||||
body = admonition_body(data_root_words(link_prose_citations(profile, notes))
|
||||
).replace("\n ", "\n")
|
||||
lines.extend(markup.details("note", "Technical notes", body.split("\n")))
|
||||
|
||||
@@ -970,16 +970,16 @@ def emulator_pages(
|
||||
lines.append("No BIOS or firmware files required.")
|
||||
if exclusion:
|
||||
lines.append("")
|
||||
lines.extend(markup.aside("info", "Why no files", [_escape_tags(str(exclusion))])[:-1])
|
||||
lines.extend(markup.aside("info", "Why no files", [escape_tags(str(exclusion))])[:-1])
|
||||
else:
|
||||
section, pages = _emulator_files_section(
|
||||
name, emu_name, profile, _EmulatorSources(db, consumers, data_names))
|
||||
lines.extend(section)
|
||||
part_pages.update(pages)
|
||||
|
||||
lines.extend(sitemeasurements.proof_section(_MEASUREMENT_ITEMS.get(name, [])))
|
||||
lines.extend(sitemeasurements.proof_section(MEASUREMENT_ITEMS.get(name, [])))
|
||||
|
||||
blocks = _render_structured_blocks(profile)
|
||||
blocks = render_structured_blocks(profile)
|
||||
if blocks:
|
||||
lines.extend(["## Profile data", "", *blocks])
|
||||
|
||||
@@ -988,12 +988,12 @@ def emulator_pages(
|
||||
lines.extend(section)
|
||||
part_pages.update(pages)
|
||||
|
||||
lines.extend(_next_block([
|
||||
lines.extend(next_block([
|
||||
"[Get the files](../which-pack.md), for the setup in use",
|
||||
"[Every system](../systems/index.md), and the files each one needs",
|
||||
"[When a game does not start](../wiki/troubleshooting.md)",
|
||||
]))
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(["", date_line()])
|
||||
return {name: "\n".join(lines) + "\n", **part_pages}
|
||||
|
||||
|
||||
@@ -1024,7 +1024,7 @@ def _card_index(
|
||||
|
||||
return [
|
||||
f"{emu_name} reads more files than one page holds: each entry below "
|
||||
f"links to its card, on {_count(len(parts), 'page')}: "
|
||||
f"links to its card, on {count_text(len(parts), 'page')}: "
|
||||
+ ", ".join(f"[{number}]({stem}.md)" for number, (stem, _e) in enumerate(parts, 1))
|
||||
+ ".",
|
||||
"",
|
||||
@@ -1075,11 +1075,11 @@ def _emulator_part_page(
|
||||
f"# {emu_name} files, part {number} of {len(parts)}",
|
||||
"",
|
||||
# The crumbs end on the emulator, read from parent:.
|
||||
f"This part holds {_count(len(files), 'entry', 'entries')}, "
|
||||
f"{_code(first)} to {_code(last)}. The other parts: {others}.",
|
||||
f"This part holds {count_text(len(files), 'entry', 'entries')}, "
|
||||
f"{code_span(first)} to {code_span(last)}. The other parts: {others}.",
|
||||
"",
|
||||
*_sectioned(files, list(range(len(files))), render),
|
||||
]
|
||||
lines.extend(_next_block([f"[{emu_name}]({name}.md), the profile and every entry"]))
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(next_block([f"[{emu_name}]({name}.md), the profile and every entry"]))
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
@@ -3,10 +3,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from model.profiles import unique_emulator_profiles
|
||||
from sitegen.emulatorcards import _named_system_link
|
||||
from sitegen.emulatorcards import named_system_link
|
||||
|
||||
|
||||
def _content_check_ceiling(profiles: dict) -> str:
|
||||
def content_check_ceiling(profiles: dict) -> str:
|
||||
"""How far content checking can reach across every profiled entry."""
|
||||
hashed = sized = neither = 0
|
||||
for profile in unique_emulator_profiles(profiles).values():
|
||||
@@ -153,7 +153,7 @@ def generate_emulators_index(profiles: dict) -> str:
|
||||
emu_name = p.get("emulator", name)
|
||||
cls = p.get("core_classification", "other")
|
||||
systems = list(dict.fromkeys(
|
||||
_named_system_link(s, "../") for s in p.get("systems") or []))
|
||||
named_system_link(s, "../") for s in p.get("systems") or []))
|
||||
files = p.get("files", [])
|
||||
sys_str = ", ".join(systems[:3])
|
||||
if len(systems) > 3:
|
||||
|
||||
+13
-13
@@ -6,8 +6,8 @@ import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from sitegen import markup
|
||||
from sitegen.render import _escape_tags, _field_text, _render_yaml_value
|
||||
from sitegen.sources import _source_ref_markdown, link_prose_citations
|
||||
from sitegen.render import escape_tags, scalar_text, render_yaml_value
|
||||
from sitegen.sources import source_ref_markdown, link_prose_citations
|
||||
|
||||
|
||||
def search_excluded(lines: list[str]) -> list[str]:
|
||||
@@ -26,7 +26,7 @@ def search_excluded(lines: list[str]) -> list[str]:
|
||||
*lines, "", "</section>", ""]
|
||||
|
||||
|
||||
def _render_platform_details(profile: dict) -> list[str]:
|
||||
def render_platform_details(profile: dict) -> list[str]:
|
||||
"""The per-platform block, one level of nesting deep."""
|
||||
lines: list[str] = []
|
||||
platform_details = profile.get("platform_details")
|
||||
@@ -48,9 +48,9 @@ def _render_platform_details(profile: dict) -> list[str]:
|
||||
def _detail_value(profile: dict, key: object, value: object) -> str:
|
||||
"""A platform detail, its citations linked at the profile's pin."""
|
||||
if key == "source_ref" and isinstance(value, (str, dict)):
|
||||
return _source_ref_markdown(profile, value)
|
||||
return source_ref_markdown(profile, value)
|
||||
if isinstance(value, str):
|
||||
return _escape_tags(link_prose_citations(profile, value))
|
||||
return escape_tags(link_prose_citations(profile, value))
|
||||
return _plain_value(value)
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ def _plain_value(value: object) -> str:
|
||||
return "none"
|
||||
if isinstance(value, (list, tuple)):
|
||||
return ", ".join(_plain_value(item) for item in value)
|
||||
return _escape_tags(str(value))
|
||||
return escape_tags(str(value))
|
||||
|
||||
|
||||
def _structured_field_text(profile: dict) -> Callable[[object, object], str]:
|
||||
@@ -74,15 +74,15 @@ def _structured_field_text(profile: dict) -> Callable[[object, object], str]:
|
||||
"""
|
||||
def text(key: object, value: object) -> str:
|
||||
if key == "source_ref" and isinstance(value, str):
|
||||
return _source_ref_markdown(profile, value)
|
||||
return source_ref_markdown(profile, value)
|
||||
if isinstance(value, str):
|
||||
return link_prose_citations(profile, _field_text(key, value))
|
||||
return _field_text(key, value)
|
||||
return link_prose_citations(profile, scalar_text(key, value))
|
||||
return scalar_text(key, value)
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def _render_structured_blocks(profile: dict) -> list[str]:
|
||||
def render_structured_blocks(profile: dict) -> list[str]:
|
||||
"""Every remaining structured field, as a collapsible section."""
|
||||
lines: list[str] = []
|
||||
_structured_blocks = [
|
||||
@@ -115,12 +115,12 @@ def _render_structured_blocks(profile: dict) -> list[str]:
|
||||
if val is None:
|
||||
continue
|
||||
body: list[str] = []
|
||||
_render_yaml_value(body, val, indent=0,
|
||||
render_yaml_value(body, val, indent=0,
|
||||
field_text=_structured_field_text(profile))
|
||||
# Closed: raw profile data, below the files (Cemu's firmware
|
||||
# titles opened the page above them).
|
||||
block = markup.details(
|
||||
"abstract", label, [_escape_tags(line) for line in body])
|
||||
"abstract", label, [escape_tags(line) for line in body])
|
||||
# A block listing hashes is the lookup's, as a card's hash lines are:
|
||||
# izapple2's ROM table put "md5" 59 times in the search, above the
|
||||
# page that explains MD5 checks.
|
||||
@@ -131,7 +131,7 @@ def _render_structured_blocks(profile: dict) -> list[str]:
|
||||
return lines
|
||||
|
||||
|
||||
def _hash_spans(value: str | list, copy: bool = False) -> str:
|
||||
def hash_spans(value: str | list, copy: bool = False) -> str:
|
||||
"""Each hash a profile accepts, in full, each with a copy button when
|
||||
*copy*.
|
||||
|
||||
|
||||
+33
-33
@@ -11,14 +11,14 @@ from model.platforms import native_layer
|
||||
from resolve.cores import resolve_platform_cores
|
||||
from resolve.nativemode import check_label
|
||||
from sitegen import markup, wanted as sitewanted
|
||||
from sitegen.cards import _PROVENANCE_LABELS, _fetch_url
|
||||
from sitegen.config import _date_line
|
||||
from sitegen.crossref import _gap_sources
|
||||
from sitegen.cards import PROVENANCE_LABELS, fetch_url
|
||||
from sitegen.config import date_line
|
||||
from sitegen.crossref import gap_sources
|
||||
from sitegen.dataexports import build_emulator_gap_report
|
||||
from sitegen.emulatorsindex import _content_check_ceiling
|
||||
from sitegen.parts import _list_pages
|
||||
from sitegen.render import _code, _count, _escape_tags
|
||||
from sitegen.sources import _source_ref_markdown
|
||||
from sitegen.emulatorsindex import content_check_ceiling
|
||||
from sitegen.parts import list_pages
|
||||
from sitegen.render import code_span, count_text, escape_tags
|
||||
from sitegen.sources import source_ref_markdown
|
||||
|
||||
|
||||
# Contributing page
|
||||
@@ -87,7 +87,7 @@ def short_hash(value: str) -> str:
|
||||
column on every screen."""
|
||||
value = str(value)
|
||||
if len(value) <= 12:
|
||||
return _code(value)
|
||||
return code_span(value)
|
||||
return f'<code title="{html.escape(value)}">{html.escape(value[:12])}</code>'
|
||||
|
||||
|
||||
@@ -102,8 +102,8 @@ def _catalogued_needs(report: dict | None) -> dict[tuple[str, str], list[str]]:
|
||||
imported romset lists that file, from a provenance report built with
|
||||
the profiles' needs."""
|
||||
return {
|
||||
need: [f"{_escape_tags(where)} `{_escape_tags(name)}`" for where, name in listed]
|
||||
for need, listed in sitewanted.catalog_listings(report, _PROVENANCE_LABELS).items()
|
||||
need: [f"{escape_tags(where)} `{escape_tags(name)}`" for where, name in listed]
|
||||
for need, listed in sitewanted.catalog_listings(report, PROVENANCE_LABELS).items()
|
||||
}
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ def _copy_cell(path: str, algos: list[str], db: dict | None) -> str:
|
||||
{},
|
||||
)
|
||||
hashes = {algo: [str(record[algo]).lower()] for algo in algos if record.get(algo)}
|
||||
shown = f"[{_code(path)}]({_fetch_url(path)})"
|
||||
shown = f"[{code_span(path)}]({fetch_url(path)})"
|
||||
return f"{shown}<br>{_hash_cell(hashes)}" if hashes else shown
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ def _render_problem_files(
|
||||
total_problems = len(missing_files) + len(untested_files) + len(mismatch_files)
|
||||
# One row per name: the page opened on "48 are missing", counted by
|
||||
# destination, above a heading that said "10 files". Both are said.
|
||||
names = _count(len(missing_files), "name")
|
||||
names = count_text(len(missing_files), "name")
|
||||
missing_said = (f"{missing_total:,} missing under {names}"
|
||||
if missing_total is not None else f"{len(missing_files)} missing")
|
||||
|
||||
@@ -197,7 +197,7 @@ def _render_problem_files(
|
||||
if missing_files:
|
||||
lines.extend([
|
||||
f'### Missing <span class="rb-badge rb-badge-danger">'
|
||||
f"{_count(len(missing_files), 'name')}</span>",
|
||||
f"{count_text(len(missing_files), 'name')}</span>",
|
||||
"",
|
||||
"Required is the platform's own flag. Category says what the "
|
||||
"platform's emulators do with the file: `bios` is firmware they "
|
||||
@@ -217,7 +217,7 @@ def _render_problem_files(
|
||||
plats = "; ".join(
|
||||
(f"[{display}](platforms/{key}.md#{system.replace(' ', '-')})"
|
||||
if key and system else display)
|
||||
+ " " + ", ".join(_code(dest) for dest in sorted(dests))
|
||||
+ " " + ", ".join(code_span(dest) for dest in sorted(dests))
|
||||
for (display, key, system), dests in sorted(f["where"].items())
|
||||
)
|
||||
cats = f["categories"]
|
||||
@@ -228,7 +228,7 @@ def _render_problem_files(
|
||||
if untested_files:
|
||||
lines.extend([
|
||||
f'### Untested <span class="rb-badge rb-badge-warning">'
|
||||
f"{_count(len(untested_files), 'file')}</span>",
|
||||
f"{count_text(len(untested_files), 'file')}</span>",
|
||||
"",
|
||||
"Present, but not the expected hash. Declared is what the platform "
|
||||
"asks for, the collection copy is what the path holds.",
|
||||
@@ -241,7 +241,7 @@ def _render_problem_files(
|
||||
plats = ", ".join(sorted(set(f["platforms"])))
|
||||
declared = f["declared"]
|
||||
lines.append(
|
||||
f"| {_code(f['name'])} | {plats} | {_reason_cell(f['reason'])} "
|
||||
f"| {code_span(f['name'])} | {plats} | {_reason_cell(f['reason'])} "
|
||||
f"| {_hash_cell(declared) or '-'} "
|
||||
f"| {_copy_cell(f['path'], list(declared) or ['md5'], db)} |"
|
||||
)
|
||||
@@ -250,7 +250,7 @@ def _render_problem_files(
|
||||
if mismatch_files:
|
||||
lines.extend([
|
||||
f'### Discrepancy <span class="rb-badge rb-badge-warning">'
|
||||
f"{_count(len(mismatch_files), 'file')}</span>",
|
||||
f"{count_text(len(mismatch_files), 'file')}</span>",
|
||||
"",
|
||||
"The platform's own check passes, but the emulator's size or "
|
||||
"hash check fails. Each row names the check that fails.",
|
||||
@@ -262,7 +262,7 @@ def _render_problem_files(
|
||||
f = mismatch_files[fname]
|
||||
plats = ", ".join(sorted(set(f["platforms"])))
|
||||
held = _held_accepted(f["discrepancy"], db)
|
||||
cell = f"[{_code(held)}]({_fetch_url(held)})" if held else "-"
|
||||
cell = f"[{code_span(held)}]({fetch_url(held)})" if held else "-"
|
||||
lines.append(f"| `{fname}` | {plats} | {_reason_cell(f['discrepancy'])} | {cell} |")
|
||||
lines.append("")
|
||||
|
||||
@@ -278,8 +278,8 @@ def _render_problem_files(
|
||||
"|------|----------|--------|--------------|",
|
||||
])
|
||||
lines.extend(
|
||||
f"| {_code(p['name'])} | {_escape_tags(p['platform'])} | {p['status']} "
|
||||
f"| {_code(p['held_by'])} |"
|
||||
f"| {code_span(p['name'])} | {escape_tags(p['platform'])} | {p['status']} "
|
||||
f"| {code_span(p['held_by'])} |"
|
||||
for p in sorted(settled, key=lambda row: (row["name"], row["platform"]))
|
||||
)
|
||||
lines.append("")
|
||||
@@ -601,9 +601,9 @@ def _source_row(m: dict, profiles: dict, coverages: dict,
|
||||
req = "yes" if m["required"] else "no"
|
||||
algorithm, _, value = m["identity"].partition(":")
|
||||
expected = f"{algorithm} {short_hash(value)}" if value else "-"
|
||||
destination = _code(m["path"]) if m["path"] != m["name"] else "-"
|
||||
destination = code_span(m["path"]) if m["path"] != m["name"] else "-"
|
||||
emulators = ", ".join(
|
||||
f"[{_escape_tags(display)}](emulators/{key}.md)"
|
||||
f"[{escape_tags(display)}](emulators/{key}.md)"
|
||||
for display, key in zip(m["emulators"], m["emu_keys"])
|
||||
)
|
||||
owner = profiles[m["emu_keys"][0]]
|
||||
@@ -613,7 +613,7 @@ def _source_row(m: dict, profiles: dict, coverages: dict,
|
||||
return (
|
||||
f"| `{m['name']}` [Have it? Upload]({upload}) | {destination} | {expected} "
|
||||
f"| {emulators} | {req} | {plat_badges} | "
|
||||
f"{_source_ref_markdown(owner, m['source_ref'])} |"
|
||||
f"{source_ref_markdown(owner, m['source_ref'])} |"
|
||||
)
|
||||
|
||||
|
||||
@@ -621,9 +621,9 @@ def _source_counted(missing: _MissingFiles) -> str:
|
||||
"""How many files there are to source, and the entries they come from."""
|
||||
req_src = [m for m in missing.rows if m["required"]]
|
||||
return (
|
||||
f"{_count(len(missing.rows), 'file')}, {len(req_src)} required."
|
||||
f"{count_text(len(missing.rows), 'file')}, {len(req_src)} required."
|
||||
+ (
|
||||
f" They come from {_count(missing.entries, 'entry', 'entries')}: a file "
|
||||
f" They come from {count_text(missing.entries, 'entry', 'entries')}: a file "
|
||||
"declared with the same hash at several places is listed once."
|
||||
if missing.entries != len(missing.rows) else ""
|
||||
)
|
||||
@@ -638,7 +638,7 @@ def _source_table(counted: str, rows: list[str], moved: dict[str, str] | None) -
|
||||
]
|
||||
if moved is None:
|
||||
return [*head, *rows, ""]
|
||||
where = _list_pages(
|
||||
where = list_pages(
|
||||
"gaps-files-to-source", "Files to source",
|
||||
f"{counted} Each is a file an emulator loads that no platform lists and "
|
||||
"the collection does not hold. Part of "
|
||||
@@ -657,7 +657,7 @@ def _bundled_note(bundled_rows: set[tuple[str, str]]) -> list[str]:
|
||||
emulators = sorted({emulator for emulator, _name in bundled_rows})
|
||||
return [
|
||||
f"{len(bundled_rows)} further files arrive with their emulator's own "
|
||||
f"package ({_escape_tags(', '.join(emulators))}): documented in the profile, not "
|
||||
f"package ({escape_tags(', '.join(emulators))}): documented in the profile, not "
|
||||
"collected, and not listed here.",
|
||||
"",
|
||||
]
|
||||
@@ -675,7 +675,7 @@ def _undeclared_gaps(report_all: dict) -> tuple[dict[str, int], int, list[tuple[
|
||||
if data["gaps"] == 0:
|
||||
continue
|
||||
total_undeclared += data["gaps"]
|
||||
for key, count in _gap_sources(data).items():
|
||||
for key, count in gap_sources(data).items():
|
||||
src_totals[key] += count
|
||||
emulator_gaps.append((emu_name, data))
|
||||
return src_totals, total_undeclared, emulator_gaps
|
||||
@@ -686,7 +686,7 @@ def _complement_rows(emulator_gaps: list[tuple[str, dict]]) -> list[str]:
|
||||
rows = []
|
||||
for emu_name, data in sorted(emulator_gaps, key=lambda x: -x[1]["gaps"]):
|
||||
display = data["emulator"]
|
||||
sources = _gap_sources(data)
|
||||
sources = gap_sources(data)
|
||||
to_source = sources["missing"]
|
||||
missing_str = (
|
||||
f'<span class="rb-badge rb-badge-danger">{to_source}</span>'
|
||||
@@ -721,7 +721,7 @@ def _complement_intro(src_totals: dict[str, int], total_undeclared: int,
|
||||
"## Files emulators load that no platform lists { #core-complement }",
|
||||
"",
|
||||
f"Files loaded by emulators but not declared by any platform. "
|
||||
f"{total_undeclared:,} files across {_count(len(emulator_gaps), 'emulator')}, "
|
||||
f"{total_undeclared:,} files across {count_text(len(emulator_gaps), 'emulator')}, "
|
||||
f"{total_available:,} available ({pct_available}), "
|
||||
f"{src_totals['bundled']:,} installed with their emulator, "
|
||||
f"{src_totals['missing']:,} to source.",
|
||||
@@ -786,7 +786,7 @@ def _not_collected_section(report_all: dict, profiles: dict, catalogued: dict |
|
||||
where = listed.get((u["emu_key"], str(u["name"]).casefold()), [])
|
||||
lines.append(
|
||||
f"| `{u['name']}` | {u['emulator']} | {_reason_cell(u['reason'])} "
|
||||
f"| {_source_ref_markdown(profiles[u['emu_key']], u['source_ref'])} "
|
||||
f"| {source_ref_markdown(profiles[u['emu_key']], u['source_ref'])} "
|
||||
f"| {', '.join(where) or '-'} |"
|
||||
)
|
||||
lines.append("")
|
||||
@@ -931,7 +931,7 @@ def generate_gap_analysis(
|
||||
"",
|
||||
_CORROBORATION_NOTE,
|
||||
"",
|
||||
_content_check_ceiling(profiles),
|
||||
content_check_ceiling(profiles),
|
||||
"",
|
||||
])
|
||||
|
||||
@@ -964,5 +964,5 @@ def generate_gap_analysis(
|
||||
|
||||
lines.extend(_not_collected_section(report_all, profiles, catalogued))
|
||||
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
+19
-18
@@ -12,21 +12,22 @@ from model.platforms import load_platform_config
|
||||
from model.registry import load_platform_registry
|
||||
from installer_build.handhelds import GROUP_PAGE
|
||||
from sitegen import handheld as sitehandheld, markup
|
||||
from sitegen.config import RELEASE_URL, REPO_URL, _REPO_ROOT
|
||||
from sitegen.config import RELEASE_URL, REPO_URL
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.descriptions import PAGE_DATA
|
||||
from sitegen.guidepage import (
|
||||
NO_ZIP_FAQ,
|
||||
_folder_words,
|
||||
_setup_relative,
|
||||
_setup_routes,
|
||||
folder_words,
|
||||
setup_relative,
|
||||
setup_routes,
|
||||
get_page_title,
|
||||
no_zip_line,
|
||||
)
|
||||
from sitegen.home import _next_block
|
||||
from sitegen.home import next_block
|
||||
from sitegen.install import has_release_pack
|
||||
from sitegen.parts import _parent_front_matter
|
||||
from sitegen.parts import parent_front_matter
|
||||
from sitegen.readme import asset_links
|
||||
from sitegen.render import _fmt_size
|
||||
from sitegen.render import fmt_size
|
||||
from sitegen.versions import release_line, version_line
|
||||
|
||||
|
||||
@@ -35,11 +36,11 @@ def _unzip_into(platform_name: str, display: str, extract_to: str | None, parts:
|
||||
writes relative to the setup's own (`system/`, `bios/`) is named as the
|
||||
setup's, with the way to find it."""
|
||||
what = "them all" if parts > 1 else "it"
|
||||
if not _setup_relative(extract_to):
|
||||
return [f"- Unzip {what} into {_folder_words(display, extract_to)}.", ""]
|
||||
if not setup_relative(extract_to):
|
||||
return [f"- Unzip {what} into {folder_words(display, extract_to)}.", ""]
|
||||
lead = GUIDES[platform_name].lead if platform_name in GUIDES else ""
|
||||
return [
|
||||
f"- Unzip {what} into {_folder_words(display, extract_to)}. "
|
||||
f"- Unzip {what} into {folder_words(display, extract_to)}. "
|
||||
f"[Where is it?](../platforms/{platform_name}.md#where-the-files-go)",
|
||||
"",
|
||||
*([lead, ""] if lead else []),
|
||||
@@ -66,13 +67,13 @@ def generate_get_page(platform_name: str) -> str:
|
||||
if released and pack and tag_date:
|
||||
PAGE_DATA[f"{releaserecord.GET_DIR}/{platform_name}.md"] = {"dateModified": "-".join(tag_date.groups())}
|
||||
if released and pack and pack.get("assets"):
|
||||
description = (f"The BIOS pack for {display}: {_fmt_size(pack['download_size'])} to "
|
||||
description = (f"The BIOS pack for {display}: {fmt_size(pack['download_size'])} to "
|
||||
"download. The address stays the same and always gives the latest ZIP.")
|
||||
else:
|
||||
description = f"The BIOS files for {display}: one command installs and checks them."
|
||||
lines = [
|
||||
"---", "search: exclude", f"description: {json.dumps(description)}",
|
||||
*_parent_front_matter((display, f"/platforms/{platform_name}/")), "---", "",
|
||||
*parent_front_matter((display, f"/platforms/{platform_name}/")), "---", "",
|
||||
f"# {title}", "",
|
||||
]
|
||||
if released and pack and pack.get("assets"):
|
||||
@@ -85,8 +86,8 @@ def generate_get_page(platform_name: str) -> str:
|
||||
asset_links(platform_name, record, REPO_URL, f"Download {display} Pack",
|
||||
button=lambda text, url: markup.button(text, url, primary=True)),
|
||||
"",
|
||||
f"- {_fmt_size(pack['download_size'])} to download, "
|
||||
f"{_fmt_size(pack['extracted_size'])} once unzipped.",
|
||||
f"- {fmt_size(pack['download_size'])} to download, "
|
||||
f"{fmt_size(pack['extracted_size'])} once unzipped.",
|
||||
*(["- Both parts are needed." if parts == 2 else f"- All {parts} parts are needed."]
|
||||
if parts > 1 else []),
|
||||
*_unzip_into(platform_name, display, extract_to, parts),
|
||||
@@ -99,7 +100,7 @@ def generate_get_page(platform_name: str) -> str:
|
||||
f"No {display} ZIP yet. The next release has one. "
|
||||
"The command installs every file and checks it.",
|
||||
"",
|
||||
*_setup_routes(platform_name, display),
|
||||
*setup_routes(platform_name, display),
|
||||
]
|
||||
elif released:
|
||||
lines += [
|
||||
@@ -112,12 +113,12 @@ def generate_get_page(platform_name: str) -> str:
|
||||
lines += [
|
||||
no_zip_line(display),
|
||||
"",
|
||||
*_setup_routes(platform_name, display),
|
||||
*setup_routes(platform_name, display),
|
||||
f"[Why no ZIP?](../{NO_ZIP_FAQ})",
|
||||
"",
|
||||
]
|
||||
lines += sitehandheld.platform_block(platform_name, _REPO_ROOT)
|
||||
lines += _next_block([
|
||||
lines += sitehandheld.platform_block(platform_name, REPO_ROOT)
|
||||
lines += next_block([
|
||||
f"[{display}](../platforms/{platform_name}.md#install): the folder, "
|
||||
"and how to run the command on the device",
|
||||
"[All installer options](../wiki/installer.md)",
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
|
||||
from model import releaserecord
|
||||
from model import siteinputs
|
||||
from model.collection import _profiles_on_disk
|
||||
from model.collection import profiles_on_disk
|
||||
from model.guides import (
|
||||
GUIDES,
|
||||
Guide,
|
||||
@@ -21,12 +21,12 @@ from model.registry import load_platform_registry
|
||||
from resolve.nativemode import digest_algorithm
|
||||
from installer_build.handhelds import GROUP_PAGE
|
||||
from sitegen import handheld as sitehandheld, markup
|
||||
from sitegen.config import _REPO_ROOT
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.guides import platform_args, terminal_tabs
|
||||
from sitegen.home import _next_block
|
||||
from sitegen.install import _installer, has_release_pack
|
||||
from sitegen.home import next_block
|
||||
from sitegen.install import installer_module, has_release_pack
|
||||
from sitegen.readme import download_links, extract_notes
|
||||
from sitegen.render import _fmt_size
|
||||
from sitegen.render import fmt_size
|
||||
from sitegen.versions import release_line, setup_version, version_line
|
||||
|
||||
|
||||
@@ -52,12 +52,12 @@ def get_page_title(platform_name: str, display: str) -> str:
|
||||
A profile listing no file (the RetroArch frontend) titles its page
|
||||
"... emulator", which no setup title repeats."""
|
||||
kind = "BIOS pack" if has_release_pack(platform_name) else "BIOS files"
|
||||
if (_profiles_on_disk().get(platform_name) or {}).get("files"):
|
||||
if (profiles_on_disk().get(platform_name) or {}).get("files"):
|
||||
return f"{kind} for {display}"
|
||||
return f"{display} {kind}"
|
||||
|
||||
|
||||
def _setup_relative(extract_to: str | None) -> bool:
|
||||
def setup_relative(extract_to: str | None) -> bool:
|
||||
"""Whether the registry writes the folder relative to the setup's own
|
||||
(`system/`, `Firmware/`), not as a path the device reads."""
|
||||
if not extract_to:
|
||||
@@ -65,17 +65,17 @@ def _setup_relative(extract_to: str | None) -> bool:
|
||||
return not extract_to.startswith(("/", "~", "<"))
|
||||
|
||||
|
||||
def _folder_words(display: str, extract_to: str | None) -> str:
|
||||
def folder_words(display: str, extract_to: str | None) -> str:
|
||||
"""The folder a pack or a copy goes into, in words: the device's path,
|
||||
or a folder of the setup named as the setup's."""
|
||||
if not extract_to:
|
||||
return "the BIOS folder"
|
||||
if _setup_relative(extract_to):
|
||||
if setup_relative(extract_to):
|
||||
return f"{display}'s `{extract_to.rstrip('/')}` folder"
|
||||
return f"`{extract_to}`"
|
||||
|
||||
|
||||
def _pack_buttons(platform_name: str, label: str = "Pack", prefix: str = "../",
|
||||
def pack_buttons(platform_name: str, label: str = "Pack", prefix: str = "../",
|
||||
display: str | None = None) -> str:
|
||||
"""The way to the platform's ZIP from its setup page: a button to its
|
||||
get/ page, the release it comes from, and the setup version its list
|
||||
@@ -135,7 +135,7 @@ def first_screen_words() -> list[str]:
|
||||
read from install.py: the one-liner opens the full screen, and the page
|
||||
showed a line menu (Enter, i, c, q) nobody saw, whose keys had changed
|
||||
since."""
|
||||
installer = _installer()
|
||||
installer = installer_module()
|
||||
# The screen it opens first: the setup found, or the list when none
|
||||
# is. Install comes on the next one, Choose systems beside it and named
|
||||
# above on the page.
|
||||
@@ -156,7 +156,7 @@ def check_pass_line() -> str:
|
||||
no file is missing or wrong (install.py EVERYTHING_IN_PLACE), read from
|
||||
the installer. Typed here, it kept "All files up to date." after the
|
||||
installer said "Everything is in place."."""
|
||||
return f"Good result: `{_installer().EVERYTHING_IN_PLACE}`"
|
||||
return f"Good result: `{installer_module().EVERYTHING_IN_PLACE}`"
|
||||
|
||||
# Under "From your computer": a device with no network installs from the ZIP
|
||||
# (`--from-pack`). The id is the one wiki/installer.md gives its section.
|
||||
@@ -233,7 +233,7 @@ def _card_route(name: str, display: str, guide: Guide) -> list[str]:
|
||||
for key in tabs}
|
||||
if guide.run != ("device",):
|
||||
lead = ("No network here? Run the command on a computer that has one, with a USB "
|
||||
f"drive's folder after `--dest`. Then copy it into {_folder_words(display, extract_to)}.")
|
||||
f"drive's folder after `--dest`. Then copy it into {folder_words(display, extract_to)}.")
|
||||
return [lead, "", *terminal_tabs(tabs, args, steps=False)]
|
||||
# A folder on the card's Linux partition: Windows and macOS show the
|
||||
# small boot partition alone, and no folder there fits --dest.
|
||||
@@ -253,7 +253,7 @@ def _get_page_line(name: str, display: str) -> list[str]:
|
||||
return [f"Link to share: [{get_page_title(name, display)}](../{get_page_link(name)})", ""]
|
||||
|
||||
|
||||
def _setup_routes(name: str, display: str, page_link: bool = False) -> list[str]:
|
||||
def setup_routes(name: str, display: str, page_link: bool = False) -> list[str]:
|
||||
"""The ways to run the command for a setup no ZIP serves first, written
|
||||
once for its setup page and its get/ page: the network folder from a
|
||||
computer, the card from a computer when the device has no network, and
|
||||
@@ -299,7 +299,7 @@ def _computer_first(name: str, guide: Guide) -> bool:
|
||||
def _ships_neogeo(name: str) -> bool:
|
||||
"""Whether the setup's files hold `neogeo.zip`, the archive a reader most
|
||||
often unzips by mistake: arcade BIOS sets are read zipped."""
|
||||
manifest = _REPO_ROOT / "install" / f"{name}.json"
|
||||
manifest = REPO_ROOT / "install" / f"{name}.json"
|
||||
if not manifest.is_file():
|
||||
return False
|
||||
files = json.loads(manifest.read_text(encoding="utf-8")).get("files", [])
|
||||
@@ -316,8 +316,8 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non
|
||||
if pack and pack.get("assets"):
|
||||
parts = len(pack["assets"])
|
||||
bullets = [
|
||||
f"{_fmt_size(pack['download_size'])} to download, "
|
||||
f"{_fmt_size(pack['extracted_size'])} once unzipped."
|
||||
f"{fmt_size(pack['download_size'])} to download, "
|
||||
f"{fmt_size(pack['extracted_size'])} once unzipped."
|
||||
]
|
||||
if parts > 1:
|
||||
bullets.append("Both parts are needed." if parts == 2 else f"All {parts} parts are needed.")
|
||||
@@ -330,13 +330,13 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non
|
||||
if guide.download_hint and not _computer_first(name, guide):
|
||||
bullets.append(guide.download_hint)
|
||||
lines += [
|
||||
_pack_buttons(name, f"Download {display} Pack"),
|
||||
pack_buttons(name, f"Download {display} Pack"),
|
||||
"",
|
||||
*(f"- {b}" for b in bullets),
|
||||
"",
|
||||
]
|
||||
elif not has_release_pack(name):
|
||||
lines += [_pack_buttons(name, display=display), ""]
|
||||
lines += [pack_buttons(name, display=display), ""]
|
||||
elif record.get("tag"):
|
||||
made_from = setup_version(name)
|
||||
lines += [
|
||||
@@ -345,7 +345,7 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non
|
||||
"",
|
||||
]
|
||||
else:
|
||||
lines += [_pack_buttons(name, f"Download {display} Pack"), ""]
|
||||
lines += [pack_buttons(name, f"Download {display} Pack"), ""]
|
||||
return [*lines, *only_some_consoles(name, "../")]
|
||||
|
||||
|
||||
@@ -353,7 +353,7 @@ def only_some_consoles(name: str, prefix: str = "") -> list[str]:
|
||||
"""The way to a smaller download, in the words Get the files uses."""
|
||||
return [
|
||||
f"Only some consoles? [Pick them]({prefix}which-pack.md?platform={name}"
|
||||
f"#only-some-consoles), or the command's **{_installer().TUI_SYSTEMS_ROW}**.",
|
||||
f"#only-some-consoles), or the command's **{installer_module().TUI_SYSTEMS_ROW}**.",
|
||||
"",
|
||||
]
|
||||
|
||||
@@ -468,14 +468,14 @@ def generate_handheld_guide(guide: HandheldGuide) -> str:
|
||||
*terminal_tabs(("windows", "macos", "linux"), args),
|
||||
SAFE_LINK,
|
||||
"",
|
||||
*_next_block([
|
||||
*next_block([
|
||||
f"[{display}]({guide.uses}.md): every folder and every file",
|
||||
"[When a game does not start](../wiki/troubleshooting.md)",
|
||||
]),
|
||||
]) + "\n"
|
||||
|
||||
|
||||
def _platform_guide(name: str, display: str, cov: dict, registry: dict, no_list: bool) -> list[str]:
|
||||
def platform_guide(name: str, display: str, cov: dict, registry: dict, no_list: bool) -> list[str]:
|
||||
"""The guide part of a platform page: folder, command, pack, check, next.
|
||||
|
||||
A system that runs only on its own device puts the computer route
|
||||
@@ -518,7 +518,7 @@ def _platform_guide(name: str, display: str, cov: dict, registry: dict, no_list:
|
||||
else:
|
||||
where = lines
|
||||
lines = [
|
||||
*_setup_routes(name, display, page_link=True),
|
||||
*setup_routes(name, display, page_link=True),
|
||||
*_guide_download(name, display, guide, extract_to, "## Download"),
|
||||
*_offline_line(name),
|
||||
*where,
|
||||
@@ -537,7 +537,7 @@ def _platform_guide(name: str, display: str, cov: dict, registry: dict, no_list:
|
||||
MISSING_IN_PLACE,
|
||||
"",
|
||||
*([guide.finish, ""] if guide.finish else []),
|
||||
*_next_block([
|
||||
*next_block([
|
||||
"[First install, step by step](../wiki/first-install.md)",
|
||||
"[When a game does not start](../wiki/troubleshooting.md)",
|
||||
]),
|
||||
|
||||
+12
-12
@@ -11,13 +11,13 @@ from model.profiles import unique_emulator_profiles
|
||||
from model.registry import load_platform_registry
|
||||
from sitegen import markup
|
||||
from sitegen.readme import demo_description, demo_facts
|
||||
from sitegen.render import _fmt_size
|
||||
from sitegen.render import fmt_size
|
||||
|
||||
|
||||
# Home page
|
||||
|
||||
|
||||
def _stat(value: str, label: str) -> list[str]:
|
||||
def stat_block(value: str, label: str) -> list[str]:
|
||||
return [
|
||||
markup.block_open("div", 'class="rb-stat"'),
|
||||
# One line, a space between: the page text read "168/168Coverage".
|
||||
@@ -27,7 +27,7 @@ def _stat(value: str, label: str) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def _group_members(coverages: dict, registry: dict, group: str) -> list[str]:
|
||||
def group_members(coverages: dict, registry: dict, group: str) -> list[str]:
|
||||
"""Registered platforms of a device group, by display name."""
|
||||
return sorted(
|
||||
(name for name in coverages if registry.get(name, {}).get("device_group") == group),
|
||||
@@ -35,7 +35,7 @@ def _group_members(coverages: dict, registry: dict, group: str) -> list[str]:
|
||||
)
|
||||
|
||||
|
||||
def _next_block(links: list[str]) -> list[str]:
|
||||
def next_block(links: list[str]) -> list[str]:
|
||||
"""Where to go from here, at the end of a page: a plain heading and a
|
||||
list. A tinted callout with a side stripe said the same as the pager."""
|
||||
return ["## Next steps", "", *(f"- {link}" for link in links), ""]
|
||||
@@ -49,7 +49,7 @@ def _tiles(registry: dict, members: list[str], display: dict[str, str], prefix:
|
||||
return markup.platform_tiles([
|
||||
*((display[name], f"{prefix}platforms/{name}.md",
|
||||
str(registry.get(name, {}).get("logo") or ""),
|
||||
GUIDES[name].runs_on or _runs_on(registry.get(name, {}), GUIDES[name]))
|
||||
GUIDES[name].runs_on or runs_on_text(registry.get(name, {}), GUIDES[name]))
|
||||
for name in members),
|
||||
*((tile.name, f"{prefix}{tile.link}", tile.logo, tile.text)
|
||||
for tile in GROUP_TILES.get(group, ())),
|
||||
@@ -64,7 +64,7 @@ def setup_picker(registry: dict, display: dict[str, str], prefix: str = "") -> l
|
||||
lines: list[str] = []
|
||||
alone: list[str] = []
|
||||
for group, (label, _description) in DEVICE_GROUPS.items():
|
||||
members = _group_keys(registry, group, display)
|
||||
members = group_keys(registry, group, display)
|
||||
if len(members) == 1 and not GROUP_TILES.get(group):
|
||||
alone += members
|
||||
elif members:
|
||||
@@ -175,10 +175,10 @@ def generate_explore_index(db: dict, coverages: dict, profiles: dict) -> str:
|
||||
"",
|
||||
markup.block_open("div", 'class="rb-stats"'),
|
||||
"",
|
||||
*_stat(f"{total_files:,}", COLLECTION_FILES_LABEL),
|
||||
*_stat(str(setup_count()), "Setups supported"),
|
||||
*_stat(str(emulator_count), "Emulators documented"),
|
||||
*_stat(_fmt_size(total_size), "Size of the collection"),
|
||||
*stat_block(f"{total_files:,}", COLLECTION_FILES_LABEL),
|
||||
*stat_block(str(setup_count()), "Setups supported"),
|
||||
*stat_block(str(emulator_count), "Emulators documented"),
|
||||
*stat_block(fmt_size(total_size), "Size of the collection"),
|
||||
"</div>",
|
||||
"",
|
||||
composition_sentence(db),
|
||||
@@ -226,7 +226,7 @@ def install_demo(variant: str = "default", name: str = "") -> list[str]:
|
||||
_OS_NAMES = {"windows": "Windows", "darwin": "macOS", "linux": "Linux"}
|
||||
|
||||
|
||||
def _runs_on(entry: dict, guide: Guide) -> str:
|
||||
def runs_on_text(entry: dict, guide: Guide) -> str:
|
||||
"""Where a setup runs, read from the systems the installer detects it on."""
|
||||
if guide.on_card:
|
||||
return "SD card, filled from a computer"
|
||||
@@ -243,7 +243,7 @@ def _runs_on(entry: dict, guide: Guide) -> str:
|
||||
return ", ".join(names)
|
||||
|
||||
|
||||
def _group_keys(registry: dict, group: str, display: dict[str, str]) -> list[str]:
|
||||
def group_keys(registry: dict, group: str, display: dict[str, str]) -> list[str]:
|
||||
return sorted(
|
||||
(k for k in registry if registry[k].get("device_group") == group),
|
||||
key=lambda k: display[k].casefold(),
|
||||
|
||||
+28
-28
@@ -16,19 +16,19 @@ from model.platforms import load_platform_config
|
||||
from model.registry import list_release_pack_platforms
|
||||
from resolve.layout import runs_standalone
|
||||
from sitegen import markup
|
||||
from sitegen.config import _REPO_ROOT
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.fields import search_excluded
|
||||
from sitegen.guides import fence, platform_args, terminal_tabs
|
||||
from sitegen.render import _code, _escape_tags
|
||||
from sitegen.sources import _source_ref_markdown
|
||||
from sitegen.render import code_span, escape_tags
|
||||
from sitegen.sources import source_ref_markdown
|
||||
|
||||
|
||||
def has_release_pack(platform_name: str) -> bool:
|
||||
"""Whether a release publishes a ZIP for the platform (`release_pack`)."""
|
||||
return platform_name in _release_pack_platforms()
|
||||
return platform_name in release_pack_platforms()
|
||||
|
||||
|
||||
def _release_pack_platforms() -> frozenset[str]:
|
||||
def release_pack_platforms() -> frozenset[str]:
|
||||
return _release_packs_in(str(siteinputs.current().platforms))
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ def _release_packs_in(platforms_dir: str) -> frozenset[str]:
|
||||
_platform_names: dict[str, str] = {}
|
||||
|
||||
|
||||
def _platform_display(name: str) -> str:
|
||||
def platform_display(name: str) -> str:
|
||||
"""A setup's name as its platform file writes it: Batocera, not batocera."""
|
||||
display = _platform_names.get(name)
|
||||
if display is None:
|
||||
@@ -87,14 +87,14 @@ def install_commands(args: str = "", indent: str = "",
|
||||
|
||||
|
||||
@functools.cache
|
||||
def _installer() -> types.ModuleType:
|
||||
def installer_module() -> types.ModuleType:
|
||||
"""install.py, read as a module: the names `--emulator` accepts are its
|
||||
own (`emulator_names`)."""
|
||||
import importlib.util
|
||||
|
||||
spec = importlib.util.spec_from_file_location("install", _REPO_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 {_REPO_ROOT / 'install.py'}")
|
||||
raise ImportError(f"cannot load {REPO_ROOT / 'install.py'}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
@@ -104,9 +104,9 @@ def _installer() -> types.ModuleType:
|
||||
def _published_emulator_names() -> dict[str, dict[str, str]]:
|
||||
"""Per published manifest, every name `--emulator` accepts there and the
|
||||
profile it stands for, as `install.py --list-emulators` prints them."""
|
||||
installer = _installer()
|
||||
installer = installer_module()
|
||||
names: dict[str, dict[str, str]] = {}
|
||||
for path in sorted((_REPO_ROOT / "install").glob("*.json")):
|
||||
for path in sorted((REPO_ROOT / "install").glob("*.json")):
|
||||
manifest = json.loads(path.read_text(encoding="utf-8"))
|
||||
names[path.stem] = installer.emulator_names(
|
||||
manifest, manifest.get("files") or [], manifest.get("omitted_files") or [])
|
||||
@@ -186,7 +186,7 @@ def _said_or(names: list[str]) -> str:
|
||||
return names[0] if len(names) == 1 else ", ".join(names[:-1]) + f" or {names[-1]}"
|
||||
|
||||
|
||||
def _install_block(name: str, profile: dict) -> list[str]:
|
||||
def install_block(name: str, profile: dict) -> list[str]:
|
||||
"""One command that installs this emulator's files where it reads them.
|
||||
|
||||
The installer finds the setup and its BIOS folder, then keeps what this
|
||||
@@ -200,7 +200,7 @@ def _install_block(name: str, profile: dict) -> list[str]:
|
||||
if not command:
|
||||
return []
|
||||
emu = str(profile.get("emulator") or name)
|
||||
shown = [_platform_display(setup) for setup in setups]
|
||||
shown = [platform_display(setup) for setup in setups]
|
||||
if profile.get("type") == "standalone":
|
||||
lead = (f"With {_said_or(shown)}: the installer finds {_said_or(shown)} and its "
|
||||
f"BIOS folder, then downloads only the files {emu} reads there and checks "
|
||||
@@ -302,11 +302,11 @@ def standalone_place(name: str, profile: dict, entry: dict, key: str = "") -> st
|
||||
return str(entry.get("standalone_path") or "")
|
||||
|
||||
|
||||
_OS_LABELS = {"windows": "Windows", "macos": "macOS", "linux": "Linux",
|
||||
OS_LABELS = {"windows": "Windows", "macos": "macOS", "linux": "Linux",
|
||||
"android": "Android", "ios": "iOS"}
|
||||
|
||||
|
||||
def _under_root(root: str, folder: str) -> str:
|
||||
def under_root(root: str, folder: str) -> str:
|
||||
"""``root`` with ``folder`` below it, as code: each alternative of
|
||||
"$XDG_CONFIG_HOME/x, else ~/.config/x", and a root written in words
|
||||
("the folder picked in the setup wizard") kept as words."""
|
||||
@@ -315,11 +315,11 @@ def _under_root(root: str, folder: str) -> str:
|
||||
for alternative in root.split(", else "):
|
||||
alternative = alternative.strip()
|
||||
if " " in alternative and "/" not in alternative and not alternative.startswith("<"):
|
||||
shown.append(f"{_code(folder + '/')} in {_escape_tags(alternative)}"
|
||||
if folder else _escape_tags(alternative))
|
||||
shown.append(f"{code_span(folder + '/')} in {escape_tags(alternative)}"
|
||||
if folder else escape_tags(alternative))
|
||||
continue
|
||||
joined = alternative.rstrip("/") + (f"/{folder}" if folder else "") + "/"
|
||||
shown.append(_code(joined))
|
||||
shown.append(code_span(joined))
|
||||
return ", else ".join(shown)
|
||||
|
||||
|
||||
@@ -355,7 +355,7 @@ def data_folder_block(name: str, profile: dict, entries: list[dict] | None = Non
|
||||
if not isinstance(root, dict) or not root.get("path"):
|
||||
continue
|
||||
path = str(root["path"])
|
||||
line = _under_root(path, _data_root_folder(name, profile, key, entries))
|
||||
line = under_root(path, _data_root_folder(name, profile, key, entries))
|
||||
if key == "android" and path.startswith("Android/data/"):
|
||||
line += ", on the internal storage."
|
||||
body = [line]
|
||||
@@ -365,9 +365,9 @@ def data_folder_block(name: str, profile: dict, entries: list[dict] | None = Non
|
||||
first = note.split(" ", 1)[0]
|
||||
if first.isalpha() and first.islower():
|
||||
note = note[:1].upper() + note[1:]
|
||||
body += ["", _escape_tags(note) + "."]
|
||||
body += ["", f"Source: {_source_ref_markdown(profile, str(root['source_ref']))}"]
|
||||
items.append((_OS_LABELS[key], body))
|
||||
body += ["", escape_tags(note) + "."]
|
||||
body += ["", f"Source: {source_ref_markdown(profile, str(root['source_ref']))}"]
|
||||
items.append((OS_LABELS[key], body))
|
||||
if len(items) == 1:
|
||||
label, body = items[0]
|
||||
return [f"On {label}: {body[0]}", *body[1:], ""]
|
||||
@@ -380,7 +380,7 @@ def data_root_words(text: str, href: str = "#data-folder") -> str:
|
||||
return re.sub(r"\bdata_root\b", f"[the data folder]({href})", text)
|
||||
|
||||
|
||||
def _platform_install_block(name: str, display: str, on_card: bool = False) -> list[str]:
|
||||
def platform_install_block(name: str, display: str, on_card: bool = False) -> list[str]:
|
||||
"""The platform's pack, installed file by file: what the ZIP holds, with
|
||||
resume, verification and only what is missing.
|
||||
|
||||
@@ -462,7 +462,7 @@ def _install_picker(declared: list[tuple[str, str]]) -> list[str]:
|
||||
+ (" selected" if (platform, system) == lead else "")
|
||||
+ f' data-sh="{attribute(_install_args(platform, system, "sh"))}" '
|
||||
f'data-ps="{attribute(_install_args(platform, system, "powershell"))}">'
|
||||
+ html.escape(_platform_display(platform) + (f" ({system})" if names[platform] > 1 else ""),
|
||||
+ html.escape(platform_display(platform) + (f" ({system})" if names[platform] > 1 else ""),
|
||||
quote=False)
|
||||
+ "</option>"
|
||||
for platform, system in declared)
|
||||
@@ -505,24 +505,24 @@ def _command_list(label: str, declared: list[tuple[str, str]], shell: str) -> li
|
||||
# inside a command.
|
||||
names = Counter(platform for platform, _system in declared)
|
||||
items = "".join(
|
||||
f"<li>{html.escape(_platform_display(platform), quote=False)}"
|
||||
f"<li>{html.escape(platform_display(platform), quote=False)}"
|
||||
+ (f" ({html.escape(system, quote=False)})" if names[platform] > 1 else "")
|
||||
+ f': <code data-copy="">{command(platform, system)}</code></li>'
|
||||
for platform, system in declared)
|
||||
return [label, "", f"<ul>{items}</ul>", ""]
|
||||
|
||||
|
||||
def _console_install_block(console: str, declared: list[tuple[str, str]]) -> list[str]:
|
||||
def console_install_block(console: str, declared: list[tuple[str, str]]) -> list[str]:
|
||||
"""Each platform's command for one console, by the system id it gives it,
|
||||
for a terminal and for PowerShell, each under its setup's name: RetroBat
|
||||
had two lines and nothing said which was for the Neo Geo."""
|
||||
if not declared:
|
||||
return []
|
||||
sh = [line for platform, system in declared for line in (
|
||||
f"# {_platform_display(platform)}",
|
||||
f"# {platform_display(platform)}",
|
||||
install_command("sh", f"--platform {platform} --system {shlex.quote(system)}"))]
|
||||
ps = [line for platform, system in declared for line in (
|
||||
f"# {_platform_display(platform)}",
|
||||
f"# {platform_display(platform)}",
|
||||
install_command("powershell", f"--platform {platform} --system {_ps_quote(system)}"))]
|
||||
# The name last: "Install the Atari System 1 files" read as a count. A
|
||||
# label naming files already reads "Install these files": "Install
|
||||
|
||||
+35
-34
@@ -11,19 +11,20 @@ from pathlib import Path
|
||||
|
||||
from core.hashing import parse_hash_list
|
||||
from model import siteinputs
|
||||
from model.collection import _slug
|
||||
from model.collection import manufacturer_slug
|
||||
from model.systemnames import system_name
|
||||
from packs.crossref import FileConsumers
|
||||
from sitegen.cards import _PROVENANCE_LABELS, _emulator_card_anchor, emulator_file_anchors
|
||||
from sitegen.config import SITE_URL, _REPO_ROOT
|
||||
from sitegen.render import _code, _slugify_anchor, card_page, emulator_card_page
|
||||
from sitegen.cards import PROVENANCE_LABELS, emulator_card_anchor, emulator_file_anchors
|
||||
from sitegen.config import SITE_URL
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.render import code_span, slugify_anchor, card_page, emulator_card_page
|
||||
from sitegen.write import write_if_changed
|
||||
|
||||
|
||||
HASH_ALGORITHMS = ("sha1", "sha256", "md5", "crc32")
|
||||
|
||||
|
||||
def _hash_values(value: object) -> list[str]:
|
||||
def sorted_hash_values(value: object) -> list[str]:
|
||||
"""Every accepted value of one hash field, lowercase.
|
||||
|
||||
A field holds one value, a list of accepted revisions, or (Recalbox) a
|
||||
@@ -32,7 +33,7 @@ def _hash_values(value: object) -> list[str]:
|
||||
return sorted(parse_hash_list(value))
|
||||
|
||||
|
||||
def _site_path(markdown_target: str) -> str:
|
||||
def site_path(markdown_target: str) -> str:
|
||||
"""A page link as generators write it (systems/sony.md#psx) as a
|
||||
site-absolute path (/retrobios/systems/sony/#psx), which resolves the same
|
||||
from any document that holds it."""
|
||||
@@ -107,7 +108,7 @@ def generate_files_page() -> str:
|
||||
])
|
||||
|
||||
|
||||
def data_directory_members(install_dir: Path = _REPO_ROOT / "install") -> dict[str, dict[str, dict]]:
|
||||
def data_directory_members(install_dir: Path = REPO_ROOT / "install") -> dict[str, dict[str, dict]]:
|
||||
"""Each data directory's files with their sha1 and size, as the install
|
||||
manifests record them for the installer to check."""
|
||||
members: dict[str, dict[str, dict]] = {}
|
||||
@@ -118,7 +119,7 @@ def data_directory_members(install_dir: Path = _REPO_ROOT / "install") -> dict[s
|
||||
return members
|
||||
|
||||
|
||||
def data_directory_revisions(data_dir: Path = _REPO_ROOT / "data") -> dict[str, dict]:
|
||||
def data_directory_revisions(data_dir: Path = REPO_ROOT / "data") -> dict[str, dict]:
|
||||
"""The revision each data directory was fetched at, as refresh_data_dirs records it."""
|
||||
path = data_dir / ".versions.json"
|
||||
if not path.is_file():
|
||||
@@ -145,8 +146,8 @@ def data_directory_origin(entry: dict, fetched: dict) -> list[str]:
|
||||
sha = str(fetched.get("sha", "")).strip('"')
|
||||
if _GIT_COMMIT.fullmatch(sha):
|
||||
repo = _GITHUB_REPO.match(url)
|
||||
commit = f"[{_code(sha[:12])}](https://github.com/{repo.group(1)}/commit/{sha})" \
|
||||
if repo else _code(sha)
|
||||
commit = f"[{code_span(sha[:12])}](https://github.com/{repo.group(1)}/commit/{sha})" \
|
||||
if repo else code_span(sha)
|
||||
branch = str(fetched.get("version", ""))
|
||||
lines.append(f"Revision: {commit}" + (
|
||||
f", the head of `{branch}` when fetched" if branch and branch != sha else ""))
|
||||
@@ -206,7 +207,7 @@ def file_location_items(
|
||||
if len(parts) < 3 or parts[0] != "bios":
|
||||
continue
|
||||
page = card_page(entry.get("path", ""), sha1)
|
||||
items.append({"sha1": sha1, "url": _site_path(f"systems/{page}.md#sha1-{sha1[:12]}")})
|
||||
items.append({"sha1": sha1, "url": site_path(f"systems/{page}.md#sha1-{sha1[:12]}")})
|
||||
# A data directory's files are listed on the page of an emulator reading
|
||||
# the tree: 2,534 hashes the packs ship were found nowhere on the site.
|
||||
owners = _data_member_owners(profiles or {})
|
||||
@@ -223,7 +224,7 @@ def file_location_items(
|
||||
known.add(sha1)
|
||||
page = page_of.get(member, owners[ref])
|
||||
items.append({"sha1": sha1,
|
||||
"url": _site_path(f"emulators/{page}.md#sha1-{sha1[:12]}")})
|
||||
"url": site_path(f"emulators/{page}.md#sha1-{sha1[:12]}")})
|
||||
return sorted(items, key=lambda item: item["sha1"])
|
||||
|
||||
|
||||
@@ -244,19 +245,19 @@ def _console_system_names(profiles: dict, coverages: dict) -> dict[tuple[str, st
|
||||
own section that folder is: a collection file is named after the console
|
||||
it is filed under. A folder no id owns, or that two names own, is left out.
|
||||
"""
|
||||
from model.systemnames import _own_section
|
||||
from model.systemnames import own_section
|
||||
from sitegen.render import system_ids
|
||||
|
||||
found: dict[tuple[str, str], set[str]] = {}
|
||||
for sys_id in system_ids(profiles, [c["config"] for c in coverages.values()]):
|
||||
own = _own_section(sys_id)
|
||||
own = own_section(sys_id)
|
||||
if own is not None:
|
||||
found.setdefault((_slug(own[0]), own[1]), set()).add(system_name(sys_id))
|
||||
found.setdefault((manufacturer_slug(own[0]), own[1]), set()).add(system_name(sys_id))
|
||||
return {key: next(iter(names)) for key, names in found.items() if len(names) == 1}
|
||||
|
||||
|
||||
def _data_member_digests(
|
||||
members: dict, data_registry: dict | None = None, root: Path = _REPO_ROOT,
|
||||
def data_member_digests(
|
||||
members: dict, data_registry: dict | None = None, root: Path = REPO_ROOT,
|
||||
) -> dict[str, dict[str, str]]:
|
||||
"""sha1 -> every hash the lookup takes, for each data directory member
|
||||
whose copy in the tree's local cache has the sha1 the manifest records.
|
||||
@@ -306,17 +307,17 @@ def retired_records(retired: dict[str, dict], files: dict, locations: list[dict]
|
||||
extra["successor"] = successor
|
||||
else:
|
||||
# The page its card was on: the reader lands among its neighbours.
|
||||
url = _site_path(f"systems/{card_page(str(record.get('path', '')), sha1)}.md")
|
||||
url = site_path(f"systems/{card_page(str(record.get('path', '')), sha1)}.md")
|
||||
for algorithm in HASH_ALGORITHMS:
|
||||
value = sha1 if algorithm == "sha1" else record.get(algorithm)
|
||||
records.extend({"value": one, "algorithm": algorithm, "layer": "retired",
|
||||
"name": str(record.get("name", "")), "sha1": sha1,
|
||||
"url": url, **extra} for one in _hash_values(value))
|
||||
"url": url, **extra} for one in sorted_hash_values(value))
|
||||
return records
|
||||
|
||||
|
||||
def _archive_member_records(entry: dict, sha1: str, url: str,
|
||||
root: Path = _REPO_ROOT) -> list[dict]:
|
||||
root: Path = REPO_ROOT) -> list[dict]:
|
||||
"""The CRC32 of each member of a collection archive, read from its
|
||||
central directory.
|
||||
|
||||
@@ -349,7 +350,7 @@ def _collection_lookup_records(
|
||||
str(info.get("sha1", "")): member.rsplit("/", 1)[-1]
|
||||
for tree in members.values() for member, info in sorted(tree.items())
|
||||
}
|
||||
member_digests = _data_member_digests(members)
|
||||
member_digests = data_member_digests(members)
|
||||
records: list[dict] = []
|
||||
for item in locations:
|
||||
sha1 = item["sha1"]
|
||||
@@ -364,13 +365,13 @@ def _collection_lookup_records(
|
||||
for algorithm in HASH_ALGORITHMS if algorithm in digests)
|
||||
continue
|
||||
parts = str(entry.get("path", "")).split("/")
|
||||
held_by = named.get((_slug(parts[1]), parts[2])) if len(parts) > 3 else None
|
||||
held_by = named.get((manufacturer_slug(parts[1]), parts[2])) if len(parts) > 3 else None
|
||||
for algorithm in HASH_ALGORITHMS:
|
||||
records.extend({
|
||||
"value": value, "algorithm": algorithm, "layer": "collection",
|
||||
"name": str(entry.get("name", "")), "sha1": sha1, "url": item["url"],
|
||||
**({"system_name": held_by} if held_by else {}),
|
||||
} for value in _hash_values(entry.get(algorithm)))
|
||||
} for value in sorted_hash_values(entry.get(algorithm)))
|
||||
records += _archive_member_records(entry, sha1, item["url"])
|
||||
return records
|
||||
|
||||
@@ -381,7 +382,7 @@ def _platform_lookup_records(coverages: dict, consumers: FileConsumers | None) -
|
||||
records: list[dict] = []
|
||||
for key, coverage in sorted(coverages.items()):
|
||||
for system_id, system in sorted((coverage["config"].get("systems") or {}).items()):
|
||||
url = _site_path(f"platforms/{key}.md#{system_id.replace(' ', '-')}")
|
||||
url = site_path(f"platforms/{key}.md#{system_id.replace(' ', '-')}")
|
||||
system_label = _lookup_system_name(system_id)
|
||||
for entry in system.get("files") or []:
|
||||
# A hash of a ROM inside the archive (zipped_file) designates
|
||||
@@ -394,7 +395,7 @@ def _platform_lookup_records(coverages: dict, consumers: FileConsumers | None) -
|
||||
"owner": key, "name": str(entry.get("name", "")), "url": url,
|
||||
**({"system_name": system_label} if system_label else {}),
|
||||
**({"sha1": archive} if archive else {}),
|
||||
} for value in _hash_values(entry.get(algorithm)))
|
||||
} for value in sorted_hash_values(entry.get(algorithm)))
|
||||
return records
|
||||
|
||||
|
||||
@@ -407,7 +408,7 @@ def _emulator_lookup_records(profiles: dict) -> list[dict]:
|
||||
entries = profile.get("files") or []
|
||||
own_systems = [str(s) for s in profile.get("systems") or []]
|
||||
for entry, anchor in zip(entries, emulator_file_anchors(entries)):
|
||||
url = _site_path(f"emulators/{emulator_card_page(key, anchor)}.md#{anchor}")
|
||||
url = site_path(f"emulators/{emulator_card_page(key, anchor)}.md#{anchor}")
|
||||
sys_id = str(entry.get("system") or "") or (
|
||||
own_systems[0] if len(own_systems) == 1 else "")
|
||||
entry_label = _lookup_system_name(sys_id) if sys_id else None
|
||||
@@ -421,7 +422,7 @@ def _emulator_lookup_records(profiles: dict) -> list[dict]:
|
||||
"value": value, "algorithm": algorithm, "layer": "emulator",
|
||||
"owner": key, "name": name, "url": url,
|
||||
**({"system_name": entry_label} if entry_label else {}),
|
||||
} for value in _hash_values(holder.get(algorithm)))
|
||||
} for value in sorted_hash_values(holder.get(algorithm)))
|
||||
return records
|
||||
|
||||
|
||||
@@ -468,8 +469,8 @@ def wanted_records(rows: list[dict]) -> list[dict]:
|
||||
knows has it, and never said the dump is wanted."""
|
||||
records = []
|
||||
for row in rows:
|
||||
label = _PROVENANCE_LABELS.get(row["catalog"], row["catalog"])
|
||||
url = _site_path(f"provenance.md#{_slugify_anchor(label)}")
|
||||
label = PROVENANCE_LABELS.get(row["catalog"], row["catalog"])
|
||||
url = site_path(f"provenance.md#{slugify_anchor(label)}")
|
||||
for algorithm in ("sha1", "md5", "crc32"):
|
||||
value = str(row.get(algorithm) or "").lower()
|
||||
if value:
|
||||
@@ -500,15 +501,15 @@ def _read_by_name(records: list[dict], files: dict, consumers: FileConsumers) ->
|
||||
entries = consumers.emulator_files.get(emulator) or []
|
||||
if index is None or index >= len(entries):
|
||||
continue
|
||||
anchor = _emulator_card_anchor(emulator, entries, index)
|
||||
url = _site_path(f"emulators/{emulator_card_page(emulator, anchor)}.md#{anchor}")
|
||||
anchor = emulator_card_anchor(emulator, entries, index)
|
||||
url = site_path(f"emulators/{emulator_card_page(emulator, anchor)}.md#{anchor}")
|
||||
name = str(entries[index].get("name", ""))
|
||||
for algorithm in HASH_ALGORITHMS:
|
||||
added.extend({
|
||||
"value": value, "algorithm": algorithm, "layer": "emulator",
|
||||
"owner": emulator, "name": name, "url": url, "sha1": sha1,
|
||||
"declared": "name",
|
||||
} for value in _hash_values(entry.get(algorithm)))
|
||||
} for value in sorted_hash_values(entry.get(algorithm)))
|
||||
return added
|
||||
|
||||
|
||||
@@ -542,7 +543,7 @@ def _held_under_every_hash(records: list[dict], files: dict, indexes: dict) -> l
|
||||
for algorithm in HASH_ALGORITHMS:
|
||||
copies.extend({**record, "value": value, "algorithm": algorithm,
|
||||
"declared": record["algorithm"]}
|
||||
for value in _hash_values(files[sha1].get(algorithm))
|
||||
for value in sorted_hash_values(files[sha1].get(algorithm))
|
||||
if value != record["value"])
|
||||
return copies
|
||||
|
||||
@@ -587,6 +588,6 @@ def data_tree_pages(ref: str, members: dict[str, dict]) -> list[tuple[str, list[
|
||||
if len(members) <= DATA_TREE_ROWS:
|
||||
return []
|
||||
names = sorted(members)
|
||||
stem = f"data-{_slugify_anchor(ref)}"
|
||||
stem = f"data-{slugify_anchor(ref)}"
|
||||
return [(stem + (f"-{n}" if n > 1 else ""), names[start:start + DATA_TREE_ROWS_PER_PAGE])
|
||||
for n, start in enumerate(range(0, len(names), DATA_TREE_ROWS_PER_PAGE), 1)]
|
||||
@@ -34,10 +34,9 @@ from pathlib import Path
|
||||
from model import measurements as mr
|
||||
from sitegen import markup
|
||||
from core.artifacts import json_text, write_if_changed
|
||||
from sitegen.render import _escape_tags
|
||||
from sitegen.render import escape_tags
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
ROOT = REPO_ROOT
|
||||
REPO = "https://github.com/Abdess/retrobios"
|
||||
EXPLORER_PAGE = "measurements.md"
|
||||
METHOD_PAGE = "wiki/measurements.md"
|
||||
@@ -455,8 +454,8 @@ def records_commit(root: Path) -> str | None:
|
||||
return commit
|
||||
|
||||
|
||||
def build(public: Path, root: Path = ROOT, emulators_dir: Path = ROOT / "emulators",
|
||||
scratch: Path = ROOT / "tmp" / "site", system_names: dict[str, str] | None = None,
|
||||
def build(public: Path, root: Path = REPO_ROOT, emulators_dir: Path = REPO_ROOT / "emulators",
|
||||
scratch: Path = REPO_ROOT / "tmp" / "site", system_names: dict[str, str] | None = None,
|
||||
repo: str = REPO, commit: str | None = None) -> Built:
|
||||
"""Write the index and the databases under the site's public folder.
|
||||
|
||||
@@ -604,7 +603,7 @@ def _text(value: object) -> str:
|
||||
ends a sentence on the site: the record keeps the words as written."""
|
||||
text = " ".join(str(value or "").split())
|
||||
text = re.sub(r";\s+(\w)", lambda m: ". " + m[1].upper(), text)
|
||||
return _escape_tags(text)
|
||||
return escape_tags(text)
|
||||
|
||||
|
||||
def _short(commit: str | None) -> str:
|
||||
|
||||
@@ -6,13 +6,13 @@ import re
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from model.collection import _slug
|
||||
from model.collection import manufacturer_slug
|
||||
from model.composition import GAME_DATA_TOPS
|
||||
from model.guides import DEVICE_GROUPS, GROUP_TILES, HANDHELD_GUIDE
|
||||
from model.profiles import unique_emulator_profiles
|
||||
from sitegen import measurements as sitemeasurements, starlight as sitestarlight
|
||||
from sitegen.config import _REPO_ROOT
|
||||
from sitegen.decorate import _front_matter
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.decorate import front_matter
|
||||
from sitegen.emulatorsindex import INITIAL_DIGITS, emulator_initial
|
||||
from sitegen.render import WIKI_SRC_DIR
|
||||
|
||||
@@ -55,7 +55,7 @@ def _system_nav(manufacturers: dict) -> list:
|
||||
arcade: list[dict] = []
|
||||
games: list[dict] = []
|
||||
for mfr in sorted(manufacturers, key=str.casefold):
|
||||
entry = {mfr: f"systems/{_slug(mfr)}.md"}
|
||||
entry = {mfr: f"systems/{manufacturer_slug(mfr)}.md"}
|
||||
if mfr in GAME_DATA_TOPS:
|
||||
games.append(entry)
|
||||
else:
|
||||
@@ -117,12 +117,12 @@ def wiki_nav(wiki_dir: Path | None = None) -> dict[str, list[NavPlace]]:
|
||||
of its tab. `nav: false` keeps a page out on purpose. A page that says
|
||||
neither raises, naming what to add.
|
||||
"""
|
||||
wiki_dir = Path(wiki_dir) if wiki_dir else _REPO_ROOT / WIKI_SRC_DIR
|
||||
wiki_dir = Path(wiki_dir) if wiki_dir else REPO_ROOT / WIKI_SRC_DIR
|
||||
tabs: dict[str, list[NavPlace]] = {level: [] for level in TABS}
|
||||
for page in sorted(wiki_dir.glob("*.md")):
|
||||
where = f"{WIKI_SRC_DIR}/{page.name}"
|
||||
text = page.read_text(encoding="utf-8")
|
||||
meta = _front_matter(text)
|
||||
meta = front_matter(text)
|
||||
level = meta.get("level")
|
||||
if level not in TABS:
|
||||
raise NavError(
|
||||
@@ -152,7 +152,7 @@ def wiki_nav(wiki_dir: Path | None = None) -> dict[str, list[NavPlace]]:
|
||||
return tabs
|
||||
|
||||
|
||||
def _overview_anchors(nav: list, docs: Path) -> dict[str, set[str]]:
|
||||
def overview_anchors(nav: list, docs: Path) -> dict[str, set[str]]:
|
||||
"""The heading ids of each overview page the navigation names, where a
|
||||
group of the sidebar finds its own section."""
|
||||
def overviews(value: object) -> Iterator[str]:
|
||||
|
||||
@@ -374,17 +374,14 @@ def page_markdown(html: str, page_url: str) -> str:
|
||||
return converter.markdown()
|
||||
|
||||
|
||||
ROOT = REPO_ROOT
|
||||
|
||||
|
||||
def build_stamp() -> dict[str, str]:
|
||||
"""The commit the site is built from and its date. CI names the commit
|
||||
in GITHUB_SHA. The date is the commit's, so two builds of one commit
|
||||
write the same bytes."""
|
||||
commit = os.environ.get("GITHUB_SHA") or subprocess.run(
|
||||
["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True,
|
||||
["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, capture_output=True, text=True,
|
||||
check=True).stdout.strip()
|
||||
date = subprocess.run(["git", "log", "-1", "--format=%cI", commit], cwd=ROOT,
|
||||
date = subprocess.run(["git", "log", "-1", "--format=%cI", commit], cwd=REPO_ROOT,
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
return {"commit": commit, "date": date}
|
||||
|
||||
|
||||
+12
-12
@@ -8,8 +8,8 @@ from pathlib import Path
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen import starlight as sitestarlight
|
||||
from sitegen.config import _date_line
|
||||
from sitegen.decorate import _front_matter
|
||||
from sitegen.config import date_line
|
||||
from sitegen.decorate import front_matter
|
||||
|
||||
|
||||
# A platform's file lists are split by the share of a page they render to,
|
||||
@@ -38,7 +38,7 @@ PUBLISHED_PARTS_FILE = (REPO_ROOT
|
||||
/ "website" / "src" / "data" / "published-parts.json")
|
||||
|
||||
|
||||
def _published_parts() -> dict[str, str]:
|
||||
def load_published_parts() -> dict[str, str]:
|
||||
if not PUBLISHED_PARTS_FILE.is_file():
|
||||
return {}
|
||||
return json.loads(PUBLISHED_PARTS_FILE.read_text(encoding="utf-8"))
|
||||
@@ -66,7 +66,7 @@ def record_parts(docs: Path, present: set[str], published: dict[str, str]) -> di
|
||||
if not page.is_file():
|
||||
page = page.with_suffix(".mdx")
|
||||
try:
|
||||
parent = _front_matter(page.read_text(encoding="utf-8")).get("parent")
|
||||
parent = front_matter(page.read_text(encoding="utf-8")).get("parent")
|
||||
except OSError:
|
||||
continue
|
||||
if isinstance(parent, dict) and parent.get("link") and rel not in found:
|
||||
@@ -79,12 +79,12 @@ def record_parts(docs: Path, present: set[str], published: dict[str, str]) -> di
|
||||
LIST_PART_BUDGET = 300_000
|
||||
|
||||
|
||||
def _characters(lines: list[str]) -> int:
|
||||
def character_count(lines: list[str]) -> int:
|
||||
return sum(len(line) + 1 for line in lines)
|
||||
|
||||
|
||||
def _blocks_in_runs(blocks: list[list[str]], budget: int,
|
||||
weigh: Callable[[list[str]], float] = _characters) -> list[list[str]]:
|
||||
def blocks_in_runs(blocks: list[list[str]], budget: int,
|
||||
weigh: Callable[[list[str]], float] = character_count) -> list[list[str]]:
|
||||
"""Blocks (table rows, folded lists) in runs of at most ``budget``, by
|
||||
default in characters, a block never cut."""
|
||||
runs: list[list[str]] = [[]]
|
||||
@@ -99,7 +99,7 @@ def _blocks_in_runs(blocks: list[list[str]], budget: int,
|
||||
return runs
|
||||
|
||||
|
||||
def _parent_front_matter(parent: tuple[str, str] | None) -> list[str]:
|
||||
def parent_front_matter(parent: tuple[str, str] | None) -> list[str]:
|
||||
"""The `parent:` front matter of a part page: the page it belongs to,
|
||||
by label and site path, which the breadcrumb and sidebar read."""
|
||||
if parent is None:
|
||||
@@ -108,7 +108,7 @@ def _parent_front_matter(parent: tuple[str, str] | None) -> list[str]:
|
||||
return ["parent:", f" label: {json.dumps(label)}", f" link: {json.dumps(link)}"]
|
||||
|
||||
|
||||
def _list_pages(
|
||||
def list_pages(
|
||||
stem: str, title: str, intro: str, head: list[str], blocks: list[list[str]],
|
||||
moved: dict[str, str], budget: int = LIST_PART_BUDGET,
|
||||
parent: tuple[str, str] | None = None,
|
||||
@@ -117,7 +117,7 @@ def _list_pages(
|
||||
opens each part, ``blocks`` are cut between parts. Returns where the list
|
||||
went, as the page it left says it. ``parent`` (label, site path) is the
|
||||
page the parts belong to, for the breadcrumb."""
|
||||
runs = _blocks_in_runs(blocks, budget)
|
||||
runs = blocks_in_runs(blocks, budget)
|
||||
stems = [stem + (f"-{n}" if n > 1 else "") for n in range(1, len(runs) + 1)]
|
||||
for n, (here, run) in enumerate(zip(stems, runs), 1):
|
||||
part = f" (part {n} of {len(runs)})" if len(runs) > 1 else ""
|
||||
@@ -125,11 +125,11 @@ def _list_pages(
|
||||
# one read as duplicates to search and to validate_site.
|
||||
opening = f"Part {n} of {len(runs)}. {intro}" if len(runs) > 1 else intro
|
||||
moved[here] = "\n".join([
|
||||
"---", "level: reference", *_parent_front_matter(parent), "---", "",
|
||||
"---", "level: reference", *parent_front_matter(parent), "---", "",
|
||||
f"# {title}{part}", "", opening, "",
|
||||
*([", ".join(f"[part {i}]({other}.md)" if other != here else f"part {i}"
|
||||
for i, other in enumerate(stems, 1)), ""] if len(runs) > 1 else []),
|
||||
*head, *run, "", _date_line(),
|
||||
*head, *run, "", date_line(),
|
||||
]) + "\n"
|
||||
if len(stems) == 1:
|
||||
return f"[a page of their own]({stems[0]}.md)"
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from model.collection import _copy_places, _slug
|
||||
from model.collection import copy_places, manufacturer_slug
|
||||
from resolve.localfile import resolution_is_hash_exact, resolve_local_file
|
||||
from resolve.ownership import BUCKET_FOLDERS, names_manufacturer
|
||||
|
||||
@@ -14,7 +14,7 @@ def _copies_by_path(db: dict) -> dict[str, set[tuple[str, str, str]]]:
|
||||
files = db.get("files", {})
|
||||
return {
|
||||
str(files[sha1].get("path", "")): where
|
||||
for sha1, where in _copy_places(db).items()
|
||||
for sha1, where in copy_places(db).items()
|
||||
}
|
||||
|
||||
|
||||
@@ -73,23 +73,23 @@ def _folders_by_name(manufacturers: dict) -> dict[str, set[tuple[str, str]]]:
|
||||
nintendo-nes, nes and the NES folder normalize alike, as do
|
||||
sega-mastersystem and Sega/Master System.
|
||||
"""
|
||||
from model.systems import _norm_system_id
|
||||
from model.systems import norm_system_id
|
||||
|
||||
index: dict[str, set[tuple[str, str]]] = {}
|
||||
for mfr, consoles in manufacturers.items():
|
||||
for console in consoles:
|
||||
spelled = console.lower().replace(" ", "-")
|
||||
for key in {
|
||||
_norm_system_id(f"{_slug(mfr)}-{spelled}"), _norm_system_id(spelled)
|
||||
norm_system_id(f"{manufacturer_slug(mfr)}-{spelled}"), norm_system_id(spelled)
|
||||
}:
|
||||
index.setdefault(key, set()).add((mfr, console))
|
||||
return index
|
||||
|
||||
|
||||
def _folder_named(sys_id: str, by_name: dict[str, set[tuple[str, str]]]) -> tuple[str, str] | None:
|
||||
from model.systems import _norm_system_id
|
||||
from model.systems import norm_system_id
|
||||
|
||||
places = by_name.get(_norm_system_id(sys_id), set())
|
||||
places = by_name.get(norm_system_id(sys_id), set())
|
||||
return next(iter(places)) if len(places) == 1 else None
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ def _profile_system_pages(
|
||||
pages[sys_id] = console_norm[sys_id]
|
||||
|
||||
|
||||
def _system_pages_from_data(
|
||||
def system_pages_from_data(
|
||||
manufacturers: dict,
|
||||
coverages: dict,
|
||||
db: dict,
|
||||
|
||||
@@ -9,29 +9,30 @@ import re
|
||||
import urllib.parse
|
||||
|
||||
from model import siteinputs
|
||||
from model.collection import _profiles_in, _profiles_on_disk
|
||||
from model.collection import profiles_in, profiles_on_disk
|
||||
from model.profiles import upstream_profile_index
|
||||
from model.systemnames import system_name
|
||||
from sitegen import entries as siteentries, markup
|
||||
from sitegen.cards import SHORT_HASH
|
||||
from sitegen.config import REPO_URL, _REPO_ROOT, _date_line
|
||||
from sitegen.fields import _hash_spans, search_excluded
|
||||
from sitegen.config import REPO_URL, date_line
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.fields import hash_spans, search_excluded
|
||||
from sitegen.parts import (
|
||||
PAGE_BYTES,
|
||||
PAGE_ELEMENTS,
|
||||
PLATFORM_PART_BUDGET,
|
||||
PLATFORM_REFERENCE_BUDGET,
|
||||
PLATFORM_SECTION_BUDGET,
|
||||
_blocks_in_runs,
|
||||
_characters,
|
||||
_parent_front_matter,
|
||||
blocks_in_runs,
|
||||
character_count,
|
||||
parent_front_matter,
|
||||
)
|
||||
from sitegen.render import (
|
||||
_code,
|
||||
_count,
|
||||
_emulator_link,
|
||||
_escape_tags,
|
||||
_fmt_size,
|
||||
code_span,
|
||||
count_text,
|
||||
emulator_link,
|
||||
escape_tags,
|
||||
fmt_size,
|
||||
card_page,
|
||||
console_href,
|
||||
)
|
||||
@@ -56,14 +57,14 @@ def _system_heading_link(sys_id: str, prefix: str = "") -> str:
|
||||
writes. A system with no section of its own is named, never sent to the
|
||||
page a storage folder chose.
|
||||
"""
|
||||
return f"{_system_named_link(sys_id, prefix)} <small>{_escape_tags(sys_id)}</small>"
|
||||
return f"{_system_named_link(sys_id, prefix)} <small>{escape_tags(sys_id)}</small>"
|
||||
|
||||
|
||||
def _system_named_link(sys_id: str, prefix: str = "") -> str:
|
||||
"""A system's name, linked to the section system_section gives."""
|
||||
from sitegen.render import system_section
|
||||
|
||||
name = _escape_tags(system_name(sys_id))
|
||||
name = escape_tags(system_name(sys_id))
|
||||
section = system_section(sys_id)
|
||||
if section is not None:
|
||||
slug, console = section
|
||||
@@ -71,11 +72,11 @@ def _system_named_link(sys_id: str, prefix: str = "") -> str:
|
||||
return name
|
||||
|
||||
|
||||
def _emulator_named_link(key: str, prefix: str = "") -> str:
|
||||
def emulator_named_link(key: str, prefix: str = "") -> str:
|
||||
"""An emulator by the name its page carries, linked to that page. A
|
||||
profile with no page (an alias, a test) is named only."""
|
||||
profile = _profiles_on_disk().get(key, {})
|
||||
label = _escape_tags(str(profile.get("emulator") or key))
|
||||
profile = profiles_on_disk().get(key, {})
|
||||
label = escape_tags(str(profile.get("emulator") or key))
|
||||
if profile.get("type") == "alias" or profile.get("role") == "test":
|
||||
return label
|
||||
return f"[{label}]({prefix}emulators/{key}.md)"
|
||||
@@ -99,17 +100,17 @@ def _served_line(f: dict, declared_sha1: str = "") -> str:
|
||||
label = "Served by" if f.get("status") == "ok" else "Held, not the declared hash"
|
||||
parts = path.split("/")
|
||||
if not sha1 or len(parts) < 3 or parts[0] != "bios":
|
||||
return f"{label}: {_code(path)}"
|
||||
return f"{label}: {code_span(path)}"
|
||||
# The card of that copy: every hash, provenance and the download.
|
||||
page = urllib.parse.quote(card_page(path, sha1))
|
||||
link = f"{label}: [{_code(path)}](../systems/{page}.md#sha1-{sha1[:12]})"
|
||||
link = f"{label}: [{code_span(path)}](../systems/{page}.md#sha1-{sha1[:12]})"
|
||||
declared = {value.strip().lower() for value in declared_sha1.split(",")}
|
||||
return link if sha1 in declared else f"{link} (sha1 `{sha1[:8]}`)"
|
||||
|
||||
|
||||
def _launcher_refs(config: dict) -> dict[str, list[str]]:
|
||||
"""Entry name, casefolded -> each launcher record that opens it, rendered."""
|
||||
from resolve.launchers import _names as launcher_names
|
||||
from resolve.launchers import record_names as launcher_names
|
||||
from resolve.launchers import bound_launchers
|
||||
from sitegen.sources import launcher_ref_markdown, list_source
|
||||
|
||||
@@ -121,7 +122,7 @@ def _launcher_refs(config: dict) -> dict[str, list[str]]:
|
||||
for record in bound_launchers(config):
|
||||
if not isinstance(record, dict) or not record.get("source_ref"):
|
||||
continue
|
||||
text = (f"{_escape_tags(str(record.get('emulator', '')))} at "
|
||||
text = (f"{escape_tags(str(record.get('emulator', '')))} at "
|
||||
f"{launcher_ref_markdown(source, str(record['source_ref']))}")
|
||||
for name in launcher_names(record):
|
||||
names = found.setdefault(name.rsplit("/", 1)[-1].casefold(), [])
|
||||
@@ -133,7 +134,7 @@ def _launcher_refs(config: dict) -> dict[str, list[str]]:
|
||||
UNPROVEN_TITLE = "Launcher records a config does not prove"
|
||||
|
||||
|
||||
def _launcher_unproven_section(config: dict) -> list[str]:
|
||||
def launcher_unproven_section(config: dict) -> list[str]:
|
||||
"""The platform's launcher records resting on a config the code does not prove.
|
||||
|
||||
A config file is proof only when the code installing it and the code
|
||||
@@ -147,9 +148,9 @@ def _launcher_unproven_section(config: dict) -> list[str]:
|
||||
return []
|
||||
source = list_source(str(config.get("source") or ""))
|
||||
body = [
|
||||
f"- {_escape_tags(row['emulator'])}, `{_escape_tags(row['passes_to'] or row['kind'])}` "
|
||||
f"- {escape_tags(row['emulator'])}, `{escape_tags(row['passes_to'] or row['kind'])}` "
|
||||
f"at {launcher_ref_markdown(source, row['source_ref'])}: "
|
||||
f"{_escape_tags('; '.join(row['missing']))}"
|
||||
f"{escape_tags('; '.join(row['missing']))}"
|
||||
for row in rows
|
||||
]
|
||||
return ["", *markup.details("note", f"{UNPROVEN_TITLE} ({len(rows)})", body)]
|
||||
@@ -270,14 +271,14 @@ def _platform_file_row(f: dict, cfg_entry: dict, hash_type: str = "",
|
||||
facts: list[str] = []
|
||||
# One code element per value: Recalbox lists accepted md5s joined by
|
||||
# commas, and each is a value a reader compares a dump with.
|
||||
facts.extend(f"{alg.upper()}: {_hash_spans(hashes[alg])}"
|
||||
facts.extend(f"{alg.upper()}: {hash_spans(hashes[alg])}"
|
||||
for alg in ("sha1", "md5", "crc32", "sha256") if hashes[alg])
|
||||
# The size closes the hash lines: a line of its own was one more
|
||||
# element per row.
|
||||
if size and facts:
|
||||
facts[-1] += f" ({_fmt_size(size)})"
|
||||
facts[-1] += f" ({fmt_size(size)})"
|
||||
elif size:
|
||||
facts.append(f"Size: {_fmt_size(size)}")
|
||||
facts.append(f"Size: {fmt_size(size)}")
|
||||
if f.get("status") == "untested" and f.get("reason"):
|
||||
facts.append(_text_html(f"Not confirmed: {f['reason']}"))
|
||||
# Not every entry is firmware: the platform may list a game's data or a
|
||||
@@ -330,10 +331,10 @@ def _page_share(lines: list[str]) -> float:
|
||||
"""The share of a page the lines render to, in thousandths: the rows
|
||||
are HTML already, so their length is their weight in bytes."""
|
||||
return max(_element_weight(lines) * 1000 / PAGE_ELEMENTS,
|
||||
_characters(lines) * 1000 / PAGE_BYTES)
|
||||
character_count(lines) * 1000 / PAGE_BYTES)
|
||||
|
||||
|
||||
def _render_platform_systems(
|
||||
def render_platform_systems(
|
||||
by_system: dict, config_files: dict, emulator_files: dict | None,
|
||||
platform: tuple[str, str] | None = None, moved: dict[str, str] | None = None,
|
||||
config: dict | None = None,
|
||||
@@ -350,7 +351,7 @@ def _render_platform_systems(
|
||||
lines: list[str] = []
|
||||
# Per-system detail sections (collapsible for large platforms)
|
||||
use_collapsible = len(by_system) > 10
|
||||
by_system_declared = _declared_by_system(config_files)
|
||||
by_system_declared = declared_by_system(config_files)
|
||||
launched = _launcher_refs(config or {})
|
||||
|
||||
sections: list[dict] = []
|
||||
@@ -358,11 +359,11 @@ def _render_platform_systems(
|
||||
ok_count = sum(1 for f in files if f["status"] == "ok")
|
||||
total = len(files)
|
||||
|
||||
sys_emus = _system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id))
|
||||
sys_emus = system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id))
|
||||
anchor = sys_id.replace(" ", "-")
|
||||
head = [f"{ok_count}/{total} files verified"]
|
||||
if sys_emus:
|
||||
emu_links = ", ".join(_emulator_named_link(e, "../") for e in sorted(sys_emus))
|
||||
emu_links = ", ".join(emulator_named_link(e, "../") for e in sorted(sys_emus))
|
||||
head[-1] += "\\"
|
||||
head.append(f"Emulators: {emu_links}")
|
||||
head.append("")
|
||||
@@ -388,8 +389,8 @@ def _render_platform_systems(
|
||||
# Measured in the share of a page the list renders to.
|
||||
size = _page_share(body)
|
||||
if use_collapsible:
|
||||
status_tag = "OK" if ok_count == total else _count(total - ok_count, "issue")
|
||||
block = markup.details("note", f"{_count(total, 'file')} ({status_tag})", body)
|
||||
status_tag = "OK" if ok_count == total else count_text(total - ok_count, "issue")
|
||||
block = markup.details("note", f"{count_text(total, 'file')} ({status_tag})", body)
|
||||
while block and not block[-1]:
|
||||
block.pop()
|
||||
else:
|
||||
@@ -425,7 +426,7 @@ def _render_platform_systems(
|
||||
if moved is not None and platform and sys_id in own_page:
|
||||
key, display = platform
|
||||
runs = [sec["head"] + _platform_file_list(run, sec["has_path"], anchor)
|
||||
for run in _blocks_in_runs([[row] for row in sec["rows"]],
|
||||
for run in blocks_in_runs([[row] for row in sec["rows"]],
|
||||
PLATFORM_PART_BUDGET, _page_share)]
|
||||
stems = [f"{key}-{anchor}" + (f"-{n}" if n > 1 else "")
|
||||
for n in range(1, len(runs) + 1)]
|
||||
@@ -434,7 +435,7 @@ def _render_platform_systems(
|
||||
# A console query landed here with no way to the console's
|
||||
# own page: the list says whose it is first, linked.
|
||||
moved[stem] = "\n".join([
|
||||
"---", *_parent_front_matter((display, f"/platforms/{key}/")), "---", "",
|
||||
"---", *parent_front_matter((display, f"/platforms/{key}/")), "---", "",
|
||||
f"# {display}: {system_name(sys_id)}{part}", "",
|
||||
f"{display}'s list for {_system_named_link(sys_id, '../')}. "
|
||||
f"Part of the [{display} page]({key}.md#{anchor}), whose other systems "
|
||||
@@ -445,12 +446,12 @@ def _render_platform_systems(
|
||||
for i, other in enumerate(stems, 1))] if len(runs) > 1 else []),
|
||||
"", "## Files", "", *markup.details("note", ROLE_LEGEND_TITLE, [ROLE_LEGEND]),
|
||||
*search_excluded(run),
|
||||
"", _date_line(),
|
||||
"", date_line(),
|
||||
]) + "\n"
|
||||
# The count and status a folded system shows in its summary,
|
||||
# linked to the page that lists the files.
|
||||
tag = "OK" if ok_count == total else _count(total - ok_count, "issue")
|
||||
count = f"{_count(total, 'file')} ({tag})"
|
||||
tag = "OK" if ok_count == total else count_text(total - ok_count, "issue")
|
||||
count = f"{count_text(total, 'file')} ({tag})"
|
||||
lines.extend([
|
||||
f"[{count}]({stems[0]}.md)" if len(stems) == 1 else f"{count}: " + ", ".join(
|
||||
f"[part {i}]({stem}.md)" for i, stem in enumerate(stems, 1)),
|
||||
@@ -465,10 +466,10 @@ def _render_platform_systems(
|
||||
|
||||
|
||||
# Platforms with an updated file published by export_native.py.
|
||||
_EXPORTED: set[str] = set()
|
||||
EXPORTED: set[str] = set()
|
||||
|
||||
|
||||
def _platform_data_links(name: str) -> str:
|
||||
def platform_data_links(name: str) -> str:
|
||||
"""The platform's own data, machine-readable: the YAML transcribed from
|
||||
its upstream list, this page's JSON and the manifest the installer reads.
|
||||
|
||||
@@ -479,8 +480,8 @@ def _platform_data_links(name: str) -> str:
|
||||
f"[YAML]({REPO_URL}/blob/main/platforms/{name}.yml)",
|
||||
f"[JSON](../api/v1/platforms/{name}.json)",
|
||||
]
|
||||
if (_REPO_ROOT / "install" / f"{name}.json").is_file():
|
||||
# The site's own copy, byte for byte (_publish_manifests).
|
||||
if (REPO_ROOT / "install" / f"{name}.json").is_file():
|
||||
# The site's own copy, byte for byte (publish_manifests).
|
||||
links.append(f"[install manifest](../api/v1/manifests/{name}.json)")
|
||||
# The installed BIOS folder for clrmamepro and RomVault.
|
||||
links.append(f"[DAT](../downloads/dat/{name}.dat)")
|
||||
@@ -489,7 +490,7 @@ def _platform_data_links(name: str) -> str:
|
||||
|
||||
def _site_profiles() -> dict[str, dict]:
|
||||
"""Every emulator profile, read once for the citations of a page."""
|
||||
return _profiles_in(str(siteinputs.current().emulators), skip_aliases=True)
|
||||
return profiles_in(str(siteinputs.current().emulators), skip_aliases=True)
|
||||
|
||||
|
||||
# Whose code a source reference cites, in one word: a platform page names
|
||||
@@ -550,7 +551,7 @@ def _category_evidence_md(evidence: dict, launched: list[str] | None = None) ->
|
||||
name = "the platform's launcher"
|
||||
refs = list(launched or [])
|
||||
else:
|
||||
name = _emulator_link(reader["emulator"], "../")
|
||||
name = emulator_link(reader["emulator"], "../")
|
||||
groups[bool(reader.get("runs_system"))].append(
|
||||
f"{name} ({', '.join(refs)})" if refs else f"{name} (by {reader['proof']})")
|
||||
if not reader.get("runs_system"):
|
||||
@@ -569,7 +570,7 @@ def _category_evidence_md(evidence: dict, launched: list[str] | None = None) ->
|
||||
# A core the site gives no page (a test core) is named, not linked.
|
||||
with_page = _profiles_with_page(str(siteinputs.current().emulators))
|
||||
cores = ("cores examined: " + ", ".join(
|
||||
_emulator_link(c, "../") if c in with_page else c for c in examined)
|
||||
emulator_link(c, "../") if c in with_page else c for c in examined)
|
||||
if examined else "no core examined")
|
||||
if evidence.get("unsettled"):
|
||||
return f"No reader found, not settled: {evidence['unsettled']} ({cores})"
|
||||
@@ -587,7 +588,7 @@ def _profiles_by_core_name() -> dict[str, list[str]]:
|
||||
@functools.cache
|
||||
def _profiles_with_page(emulators_dir: str) -> frozenset[str]:
|
||||
"""The profiles the site writes a page for: no alias, no test core."""
|
||||
profiles = _profiles_in(emulators_dir, skip_aliases=True)
|
||||
profiles = profiles_in(emulators_dir, skip_aliases=True)
|
||||
return frozenset(
|
||||
k for k, v in profiles.items() if v.get("type") != "alias" and v.get("role") != "test"
|
||||
)
|
||||
@@ -595,7 +596,7 @@ def _profiles_with_page(emulators_dir: str) -> frozenset[str]:
|
||||
|
||||
@functools.cache
|
||||
def _core_names_in(emulators_dir: str) -> dict[str, list[str]]:
|
||||
profiles = _profiles_in(emulators_dir, skip_aliases=True)
|
||||
profiles = profiles_in(emulators_dir, skip_aliases=True)
|
||||
with_page = _profiles_with_page(emulators_dir)
|
||||
return {
|
||||
core: sorted(k for k in keys if k in with_page)
|
||||
@@ -610,20 +611,20 @@ def _core_name_links(cores: list[str]) -> list[str]:
|
||||
for core in cores:
|
||||
keys = [core] if core in index.get(core, []) else index.get(core, [])
|
||||
if keys:
|
||||
links.extend(_emulator_link(k, "../") for k in keys)
|
||||
links.extend(emulator_link(k, "../") for k in keys)
|
||||
else:
|
||||
links.append(f"`{core}`")
|
||||
return links
|
||||
|
||||
|
||||
def _core_folders_section(name: str, config: dict) -> list[str]:
|
||||
def core_folders_section(name: str, config: dict) -> list[str]:
|
||||
"""Each folder the frontend hands a core, and the files the pack puts in it.
|
||||
|
||||
For a platform that names no file of its own (MinUI and its forks): the
|
||||
folders come from its launch scripts, the files from its install manifest.
|
||||
"""
|
||||
folders = config.get("core_system_dirs") or {}
|
||||
manifest = _REPO_ROOT / "install" / f"{name}.json"
|
||||
manifest = REPO_ROOT / "install" / f"{name}.json"
|
||||
files = json.loads(manifest.read_text())["files"] if manifest.is_file() else []
|
||||
lines = [
|
||||
"### Core folders",
|
||||
@@ -646,7 +647,7 @@ def _core_folders_section(name: str, config: dict) -> list[str]:
|
||||
return lines
|
||||
|
||||
|
||||
def _declared_by_system(config_files: dict) -> dict[str, list[dict]]:
|
||||
def declared_by_system(config_files: dict) -> dict[str, list[dict]]:
|
||||
"""The platform's own entries of each system, hashes included."""
|
||||
by_system: dict[str, list[dict]] = {}
|
||||
for (sys_id, _name), entries in config_files.items():
|
||||
@@ -654,7 +655,7 @@ def _declared_by_system(config_files: dict) -> dict[str, list[dict]]:
|
||||
return by_system
|
||||
|
||||
|
||||
def _system_emulators(
|
||||
def system_emulators(
|
||||
sys_id: str, emulator_files: dict | None, files: list[dict] | None = None
|
||||
) -> list[str]:
|
||||
"""The emulators a platform runs for one of its systems.
|
||||
@@ -666,9 +667,9 @@ def _system_emulators(
|
||||
an archive does not count: fbneo's boot.bin is read inside bubsys.zip,
|
||||
and RomM's Dreamcast boot.bin is not that file.
|
||||
"""
|
||||
from model.systems import _norm_system_id
|
||||
from model.systems import norm_system_id
|
||||
|
||||
norm = _norm_system_id(sys_id)
|
||||
norm = norm_system_id(sys_id)
|
||||
by_id = [name for name, data in (emulator_files or {}).items()
|
||||
if sys_id in data["systems"] or norm in data["norm"]]
|
||||
if by_id or not files:
|
||||
|
||||
@@ -7,7 +7,7 @@ from model.guides import DEVICE_GROUPS, GROUP_TILES, GUIDES
|
||||
from resolve.nativemode import check_label
|
||||
from sitegen import markup
|
||||
from sitegen.guidepage import NO_ZIP_FAQ
|
||||
from sitegen.home import _group_members
|
||||
from sitegen.home import group_members
|
||||
from sitegen.install import has_release_pack
|
||||
from sitegen.readme import release_totals
|
||||
|
||||
@@ -27,7 +27,7 @@ def generate_platform_index(coverages: dict, registry: dict | None = None) -> st
|
||||
"",
|
||||
]
|
||||
for group, (label, _description) in DEVICE_GROUPS.items():
|
||||
members = _group_members(coverages, registry, group)
|
||||
members = group_members(coverages, registry, group)
|
||||
if not members:
|
||||
continue
|
||||
# The group label names the devices, and each card carries its
|
||||
|
||||
@@ -9,25 +9,25 @@ from model.guides import GUIDES
|
||||
from model.systemnames import system_name
|
||||
from resolve.nativemode import check_label, reads_file_contents
|
||||
from sitegen import markup
|
||||
from sitegen.config import REPO_URL, _date_line
|
||||
from sitegen.config import REPO_URL, date_line
|
||||
from sitegen.decorate import level_label
|
||||
from sitegen.diagrams import local_images
|
||||
from sitegen.guidepage import _pack_buttons, _platform_guide
|
||||
from sitegen.home import _stat
|
||||
from sitegen.install import _platform_install_block
|
||||
from sitegen.guidepage import pack_buttons, platform_guide
|
||||
from sitegen.home import stat_block
|
||||
from sitegen.install import platform_install_block
|
||||
from sitegen.platformfiles import (
|
||||
ROLE_LEGEND,
|
||||
ROLE_LEGEND_TITLE,
|
||||
_EXPORTED,
|
||||
_core_folders_section,
|
||||
_declared_by_system,
|
||||
_emulator_named_link,
|
||||
_launcher_unproven_section,
|
||||
_platform_data_links,
|
||||
_render_platform_systems,
|
||||
_system_emulators,
|
||||
EXPORTED,
|
||||
core_folders_section,
|
||||
declared_by_system,
|
||||
emulator_named_link,
|
||||
launcher_unproven_section,
|
||||
platform_data_links,
|
||||
render_platform_systems,
|
||||
system_emulators,
|
||||
)
|
||||
from sitegen.render import _escape_tags, _pct
|
||||
from sitegen.render import escape_tags, percent_text
|
||||
|
||||
|
||||
# A hash a platform's list writes, in words.
|
||||
@@ -48,7 +48,7 @@ def _transcribed_row(config: dict) -> list[str]:
|
||||
note = " (a branch: the revision read is not recorded)" if moving else ""
|
||||
# Named in words: the raw URL broke into 25 lines of 8 characters
|
||||
# on a phone.
|
||||
link = (f"[{_escape_tags(listed.label)}]({listed.browse()})" if listed
|
||||
link = (f"[{escape_tags(listed.label)}]({listed.browse()})" if listed
|
||||
else f"<{transcribed}>")
|
||||
return [f"| Transcribed from | {link}{note} |"]
|
||||
|
||||
@@ -73,9 +73,9 @@ def _platform_meta_rows(name: str, config: dict, mode: str, registry: dict) -> l
|
||||
if homepage:
|
||||
rows.append(f"| Homepage | [{homepage}]({homepage}) |")
|
||||
rows.extend(_transcribed_row(config))
|
||||
if name in _EXPORTED:
|
||||
if name in EXPORTED:
|
||||
rows.append(f"| Updated file | [Download it and see the changes](../exports.md#{name}) |")
|
||||
rows.append(f"| Data | {_platform_data_links(name)} |")
|
||||
rows.append(f"| Data | {platform_data_links(name)} |")
|
||||
for cb in registry.get(name, {}).get("contributed_by", []) or []:
|
||||
username = cb.get("username", "")
|
||||
contribution = cb.get("contribution", "")
|
||||
@@ -92,17 +92,17 @@ def _platform_band(cov: dict) -> list[str]:
|
||||
"""The coverage figures above a platform's detail card."""
|
||||
config = cov["config"]
|
||||
mode = cov["mode"]
|
||||
pct = _pct(cov["present"], cov["total"])
|
||||
pct = percent_text(cov["present"], cov["total"])
|
||||
mode_badge = (
|
||||
"rb-badge-success" if reads_file_contents(mode) else "rb-badge-info"
|
||||
)
|
||||
return [
|
||||
markup.block_open("div", 'class="rb-stats"'),
|
||||
"",
|
||||
*_stat(f"{cov['present']}/{cov['total']}", f"Coverage ({pct})"),
|
||||
*_stat(str(cov["verified"]), "Verified"),
|
||||
*_stat(str(cov["missing"]), "Missing"),
|
||||
*_stat(f'<span class="rb-badge {mode_badge}">{check_label(mode, config.get("hash_rule"))}</span>',
|
||||
*stat_block(f"{cov['present']}/{cov['total']}", f"Coverage ({pct})"),
|
||||
*stat_block(str(cov["verified"]), "Verified"),
|
||||
*stat_block(str(cov["missing"]), "Missing"),
|
||||
*stat_block(f'<span class="rb-badge {mode_badge}">{check_label(mode, config.get("hash_rule"))}</span>',
|
||||
"Checked by"),
|
||||
"</div>",
|
||||
"",
|
||||
@@ -151,7 +151,7 @@ def _platform_head(name: str, cov: dict, registry: dict, no_list: bool) -> list[
|
||||
lines += [summary + (f" [{display} website]({homepage})." if homepage else ""), ""]
|
||||
|
||||
if name in GUIDES:
|
||||
lines += _platform_guide(name, display, cov, registry, no_list)
|
||||
lines += platform_guide(name, display, cov, registry, no_list)
|
||||
lines += [
|
||||
"## Reference: every file by system { #reference-every-file-by-system }",
|
||||
"",
|
||||
@@ -200,15 +200,15 @@ def generate_platform_page(
|
||||
if name not in GUIDES:
|
||||
detect = (registry.get(name, {}).get("install") or {}).get("detect") or []
|
||||
on_card = any(rule.get("method") == "card_marker" for rule in detect)
|
||||
lines.extend(["", *_platform_install_block(name, display, on_card)])
|
||||
lines.extend(["", _pack_buttons(name, f"Download {display} Pack", display=display)])
|
||||
lines.extend(["", *platform_install_block(name, display, on_card)])
|
||||
lines.extend(["", pack_buttons(name, f"Download {display} Pack", display=display)])
|
||||
lines.append("")
|
||||
|
||||
config_files, by_system = _platform_declarations(cov)
|
||||
|
||||
if no_list:
|
||||
lines.extend(_core_folders_section(name, config))
|
||||
if _own_list_only(config):
|
||||
lines.extend(core_folders_section(name, config))
|
||||
if own_list_only(config):
|
||||
lines.extend([f"**Cores:** {OWN_LIST_ONLY}", ""])
|
||||
|
||||
# System summary table (quick navigation)
|
||||
@@ -220,7 +220,7 @@ def generate_platform_page(
|
||||
"|--------|-------|--------|-----------|",
|
||||
]
|
||||
)
|
||||
by_system_declared = _declared_by_system(config_files)
|
||||
by_system_declared = declared_by_system(config_files)
|
||||
for sys_id, files in sorted(by_system.items()):
|
||||
ok_count = sum(1 for f in files if f["status"] == "ok")
|
||||
total = len(files)
|
||||
@@ -232,18 +232,18 @@ def generate_platform_page(
|
||||
f'<span class="rb-badge rb-badge-warning">'
|
||||
f'{non_ok} issue{"s" if non_ok > 1 else ""}</span>'
|
||||
)
|
||||
sys_emus = _system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id))
|
||||
sys_emus = system_emulators(sys_id, emulator_files, by_system_declared.get(sys_id))
|
||||
anchor = sys_id.replace(" ", "-")
|
||||
# Named and linked as the detail blocks below do: the column held
|
||||
# profile ids, none of 1,463 linked.
|
||||
emu_str = ", ".join(_emulator_named_link(e, "../") for e in sorted(sys_emus)[:3])
|
||||
emu_str = ", ".join(emulator_named_link(e, "../") for e in sorted(sys_emus)[:3])
|
||||
if len(sys_emus) > 3:
|
||||
emu_str += f" [+{len(sys_emus) - 3}](#{anchor})"
|
||||
# The name a reader filters on, the id the list writes beside it.
|
||||
# The id and the count are no words a reader searches for: indexed,
|
||||
# every platform page answered a system id before its system's page.
|
||||
lines.append(
|
||||
f"| [{_escape_tags(system_name(sys_id))}](#{anchor}) "
|
||||
f"| [{escape_tags(system_name(sys_id))}](#{anchor}) "
|
||||
f"<small data-pagefind-ignore>{sys_id}</small> "
|
||||
f"| <span data-pagefind-ignore>{ok_count}/{total}</span> | {status} | {emu_str} |"
|
||||
)
|
||||
@@ -252,12 +252,12 @@ def generate_platform_page(
|
||||
lines.extend(markup.details("note", ROLE_LEGEND_TITLE, [ROLE_LEGEND]))
|
||||
|
||||
lines.extend(
|
||||
_render_platform_systems(by_system, config_files, emulator_files,
|
||||
render_platform_systems(by_system, config_files, emulator_files,
|
||||
(name, display), moved, config)
|
||||
)
|
||||
lines.extend(_launcher_unproven_section(config))
|
||||
lines.extend(launcher_unproven_section(config))
|
||||
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
@@ -266,6 +266,6 @@ def generate_platform_page(
|
||||
OWN_LIST_ONLY = "None. Its own list is the whole truth: no core profile adds a file."
|
||||
|
||||
|
||||
def _own_list_only(config: dict) -> bool:
|
||||
def own_list_only(config: dict) -> bool:
|
||||
"""The platform declares `cores: []`: its own list decides alone."""
|
||||
return isinstance(config.get("cores"), list) and not config["cores"]
|
||||
@@ -9,10 +9,10 @@ from datetime import datetime
|
||||
from model.composition import compute_composition, count_catalog_matched
|
||||
from acquire.provenance import distinct_missing
|
||||
from sitegen import entries as siteentries, markup
|
||||
from sitegen.cards import _PROVENANCE_LABELS, _ROMSET_SOURCES
|
||||
from sitegen.config import _date_line
|
||||
from sitegen.parts import _list_pages
|
||||
from sitegen.render import _count, _escape_tags, _slugify_anchor
|
||||
from sitegen.cards import PROVENANCE_LABELS, ROMSET_SOURCES
|
||||
from sitegen.config import date_line
|
||||
from sitegen.parts import list_pages
|
||||
from sitegen.render import count_text, escape_tags, slugify_anchor
|
||||
|
||||
|
||||
_PROVENANCE_HOMES = {
|
||||
@@ -46,7 +46,7 @@ def _date_in_words(stamp: str) -> str:
|
||||
try:
|
||||
day = datetime.strptime(str(stamp)[:10], "%Y-%m-%d")
|
||||
except ValueError:
|
||||
return _escape_tags(str(stamp))
|
||||
return escape_tags(str(stamp))
|
||||
return f'<time datetime="{day:%Y-%m-%d}">{day.day} {day:%B %Y}</time>'
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ def generate_provenance_page(
|
||||
total_files = compute_composition(db)["systems"]["files"]
|
||||
# When each catalog was read: a 76-day-old snapshot showed no age.
|
||||
as_of = ", ".join(
|
||||
f"{_PROVENANCE_LABELS.get(source, source)} {_date_in_words(data['imported_at'])}"
|
||||
f"{PROVENANCE_LABELS.get(source, source)} {_date_in_words(data['imported_at'])}"
|
||||
for source, data in report.items() if data.get("imported_at")
|
||||
)
|
||||
|
||||
@@ -120,7 +120,7 @@ def generate_provenance_page(
|
||||
]
|
||||
|
||||
for source, data in report.items():
|
||||
label = _PROVENANCE_LABELS.get(source, source)
|
||||
label = PROVENANCE_LABELS.get(source, source)
|
||||
home = _PROVENANCE_HOMES.get(source, "")
|
||||
in_scope = data["matched"] + len(data["missing"])
|
||||
pct = 100 * data["matched"] / in_scope if in_scope else 0
|
||||
@@ -145,7 +145,7 @@ def generate_provenance_page(
|
||||
out_of_scope = {s: d["out_of_scope"] for s, d in report.items() if d["out_of_scope"]}
|
||||
if out_of_scope:
|
||||
detail = ", ".join(
|
||||
f"{_PROVENANCE_LABELS.get(s, s)} {c:,}" for s, c in sorted(out_of_scope.items())
|
||||
f"{PROVENANCE_LABELS.get(s, s)} {c:,}" for s, c in sorted(out_of_scope.items())
|
||||
)
|
||||
lines.extend(
|
||||
[
|
||||
@@ -187,7 +187,7 @@ def generate_provenance_page(
|
||||
|
||||
lines.extend(_derivable_section(derived_entries, derivable))
|
||||
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
@@ -224,7 +224,7 @@ def _wanted_dat_table(entries: list) -> list[str]:
|
||||
# Where an emulator's romset already carries the dump.
|
||||
for hit in entry.get("romsets", []):
|
||||
desc += (
|
||||
f" Ships in {_ROMSET_SOURCES.get(hit['source'], hit['source'])} "
|
||||
f" Ships in {ROMSET_SOURCES.get(hit['source'], hit['source'])} "
|
||||
f"`{hit['archive']}` as `{hit['member']}`."
|
||||
)
|
||||
table.append(f"| `{name}` | {desc} | `{sha1}` |")
|
||||
@@ -233,22 +233,22 @@ def _wanted_dat_table(entries: list) -> list[str]:
|
||||
|
||||
def _wanted_section(source: str, data: dict, derived: int, moved: dict[str, str] | None) -> list[str]:
|
||||
"""A catalog's missing dumps, by DAT, or a line naming the page they went to."""
|
||||
label = _PROVENANCE_LABELS.get(source, source)
|
||||
label = PROVENANCE_LABELS.get(source, source)
|
||||
by_dat: dict[str, list] = {}
|
||||
for entry in data["missing"]:
|
||||
for dat in entry.get("dats") or [entry.get("dat", "")]:
|
||||
by_dat.setdefault(dat, []).append(entry)
|
||||
lines = [f"### {label}", ""]
|
||||
if moved is not None:
|
||||
where = _list_pages(
|
||||
f"provenance-{_slugify_anchor(source)}", f"Wanted from {label}",
|
||||
where = list_pages(
|
||||
f"provenance-{slugify_anchor(source)}", f"Wanted from {label}",
|
||||
f"Dumps {label} catalogues and the collection lacks. Part of "
|
||||
f"[Dump provenance](provenance.md#{_slugify_anchor(label)}).",
|
||||
f"[Dump provenance](provenance.md#{slugify_anchor(label)}).",
|
||||
[], [_wanted_list(source, label, data, by_dat, derived)],
|
||||
moved, parent=("Dump provenance", "/provenance/"),
|
||||
)
|
||||
lines.extend([
|
||||
f"{_count(len(data['missing']), 'dump')} in {_count(len(by_dat), 'DAT')}: "
|
||||
f"{count_text(len(data['missing']), 'dump')} in {count_text(len(by_dat), 'DAT')}: "
|
||||
f"listed on {where}.", "",
|
||||
])
|
||||
return lines
|
||||
@@ -293,10 +293,10 @@ def _wanted_list(source: str, label: str, data: dict, by_dat: dict[str, list],
|
||||
missing = data["missing"]
|
||||
held = data["matched"]
|
||||
reached = held + len(missing) + derived
|
||||
dats = _count(len(data["covered_dats"]), "DAT")
|
||||
dats = count_text(len(data["covered_dats"]), "DAT")
|
||||
lines = [
|
||||
f"Held: **{held:,}** of {reached:,}, in the {dats} the collection reaches. "
|
||||
f"Wanted: **{len(missing):,}**, from {_count(len(by_dat), 'DAT')}.",
|
||||
f"Wanted: **{len(missing):,}**, from {count_text(len(by_dat), 'DAT')}.",
|
||||
"",
|
||||
]
|
||||
if derived:
|
||||
@@ -315,7 +315,7 @@ def _wanted_list(source: str, label: str, data: dict, by_dat: dict[str, list],
|
||||
desc = markup.inline_html(entry.get("description") or "")
|
||||
for hit in entry.get("romsets", []):
|
||||
desc += markup.inline_html(
|
||||
f" Ships in {_ROMSET_SOURCES.get(hit['source'], hit['source'])} "
|
||||
f" Ships in {ROMSET_SOURCES.get(hit['source'], hit['source'])} "
|
||||
f"`{hit['archive']}` as `{hit['member']}`.")
|
||||
in_dats = ", ".join(html.escape(d) for d in (entry.get("dats") or [entry.get("dat", "")]))
|
||||
sha1 = html.escape(entry.get("sha1") or "-")
|
||||
@@ -333,10 +333,10 @@ def _wanted_list(source: str, label: str, data: dict, by_dat: dict[str, list],
|
||||
f'<td class="rb-hash" {skip}>{sha1}</td></tr>')
|
||||
heads = ["Name", "DAT", "Description", "SHA1"]
|
||||
lines.extend([
|
||||
siteentries.filter_box(f"rb-wanted-filter-{_slugify_anchor(source)}",
|
||||
siteentries.filter_box(f"rb-wanted-filter-{slugify_anchor(source)}",
|
||||
"dumps", heads, len(rows)),
|
||||
'<details class="rb-details rb-details-note">',
|
||||
f"<summary>All {_count(len(rows), 'wanted dump')}</summary>",
|
||||
f"<summary>All {count_text(len(rows), 'wanted dump')}</summary>",
|
||||
'<table class="rb-wanted" data-rb-stack="true">',
|
||||
"<thead><tr>" + "".join(f'<th scope="col">{h}</th>' for h in heads) + "</tr></thead>",
|
||||
"<tbody>", *rows, "</tbody>", "</table>", "</details>", "",
|
||||
|
||||
+11
-11
@@ -7,8 +7,8 @@ import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from model import releaserecord
|
||||
from sitegen.config import _REPO_ROOT
|
||||
from sitegen.write import _record, write_if_changed
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.write import record_written, write_if_changed
|
||||
|
||||
|
||||
def write_release_advertised(generated: Path) -> None:
|
||||
@@ -26,7 +26,7 @@ def write_release_advertised(generated: Path) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _publish_manifests(api: Path) -> list[tuple]:
|
||||
def publish_manifests(api: Path) -> list[tuple]:
|
||||
"""The install manifests and the release record, beside the API.
|
||||
|
||||
The platform's list says what a setup checks. The manifest says what its
|
||||
@@ -38,34 +38,34 @@ def _publish_manifests(api: Path) -> list[tuple]:
|
||||
folder = api / "manifests"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
assets: list[tuple] = []
|
||||
for source in sorted((_REPO_ROOT / "install").glob("*.json")):
|
||||
for source in sorted((REPO_ROOT / "install").glob("*.json")):
|
||||
target = folder / source.name
|
||||
shutil.copy2(source, target)
|
||||
_record(target)
|
||||
record_written(target)
|
||||
assets.append((target, f"Install manifest: {source.stem}", "application/json",
|
||||
"schemas/install-manifest.schema.json"))
|
||||
# The target lists install.py --target reads: no catalog entry, and
|
||||
# api/v1/targets/ answered 404.
|
||||
targets = api / "targets"
|
||||
targets.mkdir(parents=True, exist_ok=True)
|
||||
for source in sorted((_REPO_ROOT / "install" / "targets").glob("*.json")):
|
||||
for source in sorted((REPO_ROOT / "install" / "targets").glob("*.json")):
|
||||
shutil.copy2(source, targets / source.name)
|
||||
_record(targets / source.name)
|
||||
record_written(targets / source.name)
|
||||
assets.append((targets / source.name, f"Target list: {source.stem}",
|
||||
"application/json", "schemas/target-manifest.schema.json"))
|
||||
# Every change each updated platform file carries, for a maintainer who
|
||||
# reviews them by script: the Exports page linked only the files.
|
||||
exports = api / "exports"
|
||||
exports.mkdir(parents=True, exist_ok=True)
|
||||
for source in sorted((_REPO_ROOT / "exports").glob("*.json")):
|
||||
for source in sorted((REPO_ROOT / "exports").glob("*.json")):
|
||||
shutil.copy2(source, exports / source.name)
|
||||
_record(exports / source.name)
|
||||
record_written(exports / source.name)
|
||||
assets.append((exports / source.name, f"Updated platform file, its changes: {source.stem}",
|
||||
"application/json", None))
|
||||
release = _REPO_ROOT / "release.json"
|
||||
release = REPO_ROOT / "release.json"
|
||||
if release.is_file():
|
||||
shutil.copy2(release, api / "release.json")
|
||||
_record(api / "release.json")
|
||||
record_written(api / "release.json")
|
||||
assets.append((api / "release.json", "Latest release: packs, sizes and assets",
|
||||
"application/json", "schemas/release.schema.json"))
|
||||
return assets
|
||||
@@ -122,11 +122,10 @@ def compute_coverage(
|
||||
}
|
||||
|
||||
|
||||
_REPO = REPO_ROOT
|
||||
# The site and the README read the same coverage: the first generator to run
|
||||
# stores it here and the second reads it back, instead of verifying every
|
||||
# platform twice (about a minute of the site build).
|
||||
COVERAGE_CACHE_DIR = _REPO / "tmp" / "coverage-cache"
|
||||
COVERAGE_CACHE_DIR = REPO_ROOT / "tmp" / "coverage-cache"
|
||||
_COVERAGE_CACHE_FORMAT = "3"
|
||||
|
||||
|
||||
@@ -150,12 +149,12 @@ def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> s
|
||||
|
||||
add_file(db_path.resolve())
|
||||
for root, pattern in ((Path(platforms_dir), "*"), (Path(emulators_dir), "*.yml"),
|
||||
(_REPO / "scripts", "*.py"), (_REPO / "install", "*.json"),
|
||||
(_REPO / "recipes", "*.json")):
|
||||
(REPO_ROOT / "scripts", "*.py"), (REPO_ROOT / "install", "*.json"),
|
||||
(REPO_ROOT / "recipes", "*.json")):
|
||||
for path in sorted(p for p in root.resolve().rglob(pattern) if p.is_file()):
|
||||
add_file(path)
|
||||
for path in (_REPO / ".gitignore", _REPO / "_mame_clones.json",
|
||||
_REPO / "data" / ".versions.json"):
|
||||
for path in (REPO_ROOT / ".gitignore", REPO_ROOT / "_mame_clones.json",
|
||||
REPO_ROOT / "data" / ".versions.json"):
|
||||
add_file(path)
|
||||
digest.update(b"offline\0" + (b"1" if os.environ.get("RETROBIOS_OFFLINE") else b"0") + b"\n")
|
||||
large = Path(LARGE_FILES_CACHE).resolve()
|
||||
@@ -164,7 +163,7 @@ def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> s
|
||||
if path.is_file():
|
||||
stat = path.stat()
|
||||
digest.update(f"{path.name}\0{stat.st_size}\0{stat.st_mtime_ns}\n".encode())
|
||||
bios = _REPO / "bios"
|
||||
bios = REPO_ROOT / "bios"
|
||||
for path in sorted(bios.rglob("*")):
|
||||
if path.is_file():
|
||||
stat = path.stat()
|
||||
@@ -205,7 +204,7 @@ def platform_coverages(
|
||||
else:
|
||||
if stored.get("platforms") == names:
|
||||
coverages = stored["coverages"]
|
||||
print(f" coverage read from {cache.relative_to(_REPO)}")
|
||||
print(f" coverage read from {cache.relative_to(REPO_ROOT)}")
|
||||
if coverages is None:
|
||||
coverages = {}
|
||||
for name in names:
|
||||
@@ -815,7 +814,7 @@ def ci_install_lines() -> tuple[str, str]:
|
||||
could pass on releases CI never installs. Read from the workflow, the
|
||||
two cannot disagree. The second line is the Python 3.8 one.
|
||||
"""
|
||||
text = (_REPO / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
|
||||
text = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
|
||||
main = re.search(r'^\s*run: (pip install pyyaml "jsonschema.*markdown.*)$', text, re.M)
|
||||
floor = re.search(r"^\s*run: (python3\.8 -m pip install .*)$", text, re.M)
|
||||
if main is None or floor is None:
|
||||
@@ -964,7 +963,7 @@ def generate_contributing() -> str:
|
||||
)
|
||||
|
||||
|
||||
def _write(readme: str) -> None:
|
||||
def write_readme(readme: str) -> None:
|
||||
status = "Generated" if write_if_changed("README.md", readme) else "Unchanged"
|
||||
print(f"{status} ./README.md")
|
||||
|
||||
|
||||
@@ -5,14 +5,14 @@ from __future__ import annotations
|
||||
import json
|
||||
|
||||
from model.profiles import unique_emulator_profiles
|
||||
from sitegen.home import _next_block
|
||||
from sitegen.home import next_block
|
||||
from sitegen.readme import contributing_text
|
||||
|
||||
|
||||
def generate_contributing() -> str:
|
||||
return contributing_text(
|
||||
lambda page: f"{page}.md", "# Contributing", "on this site"
|
||||
) + "\n" + "\n".join(_next_block([
|
||||
) + "\n" + "\n".join(next_block([
|
||||
"[Profiling an emulator](wiki/profiling.md), the first task most "
|
||||
"contributions start from",
|
||||
]))
|
||||
@@ -45,7 +45,7 @@ def generate_not_found() -> str:
|
||||
|
||||
|
||||
def reference_next() -> str:
|
||||
return "\n" + "\n".join(_next_block([
|
||||
return "\n" + "\n".join(next_block([
|
||||
"[Reference index](wiki/index.md), every reference page in one list",
|
||||
"For contributors: [How to contribute](contributing.md)",
|
||||
]))
|
||||
|
||||
+51
-54
@@ -9,16 +9,16 @@ from collections.abc import Callable
|
||||
from model import siteinputs
|
||||
from sitegen import markup
|
||||
from core.paths import REPO_ROOT
|
||||
from model.collection import _PROGRAM_TOPS, _card_moves, _slug
|
||||
from model.collection import PROGRAM_TOPS, card_moves, manufacturer_slug
|
||||
from model.systemnames import (
|
||||
SYSTEM_PARENTS,
|
||||
_boards_built,
|
||||
_console_anchors,
|
||||
_ensure_console_sections,
|
||||
_own_section,
|
||||
_program_names,
|
||||
_section_pairs,
|
||||
_sections_by_name,
|
||||
boards_built,
|
||||
console_anchors,
|
||||
ensure_console_sections,
|
||||
own_section,
|
||||
known_program_names,
|
||||
section_pairs,
|
||||
sections_by_name,
|
||||
system_name,
|
||||
)
|
||||
|
||||
@@ -34,7 +34,7 @@ _icon_available: dict[str, bool] = {}
|
||||
_CODE_SPAN = re.compile(r"(`+).+?\1", re.S)
|
||||
|
||||
|
||||
def _code(value: object) -> str:
|
||||
def code_span(value: object) -> str:
|
||||
"""A value as an inline code span it cannot leave.
|
||||
|
||||
Markdown shows HTML inside a code span as text, so the one way out is a
|
||||
@@ -44,12 +44,12 @@ def _code(value: object) -> str:
|
||||
return "`" + str(value).replace("`", "'") + "`"
|
||||
|
||||
|
||||
def _count(number: int, noun: str, plural: str = "") -> str:
|
||||
def count_text(number: int, noun: str, plural: str = "") -> str:
|
||||
"""A count and its noun, singular for one: the site printed "1 files" 234 times."""
|
||||
return f"{number:,} {noun if number == 1 else plural or noun + 's'}"
|
||||
|
||||
|
||||
def _escape_tags(text: str) -> str:
|
||||
def escape_tags(text: str) -> str:
|
||||
"""Show a placeholder such as ``<system_dir>`` as it was written.
|
||||
|
||||
Profile prose names paths with angle brackets. Passed through as HTML
|
||||
@@ -70,12 +70,12 @@ def _escape_tags(text: str) -> str:
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _admonition_body(text: str) -> str:
|
||||
def admonition_body(text: str) -> str:
|
||||
"""Indent prose without turning source tokens such as ``#if`` into H1s."""
|
||||
escaped = re.sub(r"(?m)^(\s*)#", r"\1\\#", _escape_tags(text))
|
||||
escaped = re.sub(r"(?m)^(\s*)#", r"\1\\#", escape_tags(text))
|
||||
return escaped.replace("\n", "\n ")
|
||||
|
||||
def _icon_name(manufacturer: str, console_name: str) -> str:
|
||||
def console_icon_name(manufacturer: str, console_name: str) -> str:
|
||||
return f"{manufacturer} - {console_name}".replace("/", " ")
|
||||
|
||||
def _icon_url(icon_name: str) -> str:
|
||||
@@ -101,15 +101,15 @@ def system_icon_markdown(manufacturer: str, console_name: str) -> str:
|
||||
The link names the upstream file: ``sitediagrams.localize_images``
|
||||
points it at the local copy, whose source is recorded beside it.
|
||||
"""
|
||||
name = _icon_name(manufacturer, console_name)
|
||||
name = console_icon_name(manufacturer, console_name)
|
||||
if not _icon_available.get(name):
|
||||
return ""
|
||||
return markup.image(console_name, _icon_url(name), width="24") + " "
|
||||
|
||||
# Global index: maps system_id -> (manufacturer_slug, console_name) for cross-linking
|
||||
_system_page_map: dict[str, tuple[str, str]] = {}
|
||||
system_page_map: dict[str, tuple[str, str]] = {}
|
||||
|
||||
def _slugify_anchor(text: str) -> str:
|
||||
def slugify_anchor(text: str) -> str:
|
||||
"""Slugify text for MkDocs anchor compatibility."""
|
||||
import re
|
||||
|
||||
@@ -129,29 +129,29 @@ def set_system_page_map(mapping: dict[str, tuple[str, str]]) -> None:
|
||||
derived from it here. Kept anywhere else, it outlived a table of the same
|
||||
size and linked to the pages of the previous one.
|
||||
"""
|
||||
from model.systems import _norm_system_id
|
||||
from model.systems import norm_system_id
|
||||
|
||||
_system_page_map.clear()
|
||||
_system_page_map.update(mapping)
|
||||
system_page_map.clear()
|
||||
system_page_map.update(mapping)
|
||||
_norm_page_map.clear()
|
||||
for known, page in _system_page_map.items():
|
||||
key = _norm_system_id(known)
|
||||
for known, page in system_page_map.items():
|
||||
key = norm_system_id(known)
|
||||
if _norm_page_map.get(key, page) != page:
|
||||
_norm_page_map[key] = None
|
||||
else:
|
||||
_norm_page_map[key] = page
|
||||
|
||||
|
||||
def _page_by_norm(sys_id: str) -> tuple[str, str] | None:
|
||||
def page_by_norm(sys_id: str) -> tuple[str, str] | None:
|
||||
"""The page an id leads to under another spelling of the same system.
|
||||
|
||||
Emulator cards name sega-megadrive or sinclair-zxspectrum, the pages are
|
||||
keyed by the platforms' spellings: 2,431 of 4,195 cards had no link. A
|
||||
spelling two pages share leads nowhere rather than to either.
|
||||
"""
|
||||
from model.systems import _norm_system_id
|
||||
from model.systems import norm_system_id
|
||||
|
||||
return _norm_page_map.get(_norm_system_id(sys_id))
|
||||
return _norm_page_map.get(norm_system_id(sys_id))
|
||||
|
||||
|
||||
# A manufacturer page too large for one page is a summary, each console on
|
||||
@@ -189,8 +189,8 @@ def console_anchor(manufacturer: str, console: str) -> str:
|
||||
"""The id of a console's heading on its manufacturer's page."""
|
||||
from core.anchors import toc_slug
|
||||
|
||||
key = (_slug(manufacturer), console)
|
||||
return _console_anchors.get(key) or toc_slug(console)
|
||||
key = (manufacturer_slug(manufacturer), console)
|
||||
return console_anchors.get(key) or toc_slug(console)
|
||||
|
||||
|
||||
def console_href(slug: str, console: str, prefix: str = "") -> str:
|
||||
@@ -219,7 +219,7 @@ def card_page(path: str, sha1: str) -> str:
|
||||
board = arcade_board(sha1)
|
||||
if board in _board_sections:
|
||||
return f"arcade-{board_slug(board)}"
|
||||
slug, console = _card_moves.get((slug, console, str(sha1)), (slug, console))
|
||||
slug, console = card_moves.get((slug, console, str(sha1)), (slug, console))
|
||||
return _card_pages.get((slug, console, sha1), slug)
|
||||
|
||||
|
||||
@@ -268,25 +268,25 @@ def system_section(sys_id: str) -> tuple[str, str] | None:
|
||||
def _section_without_boards(sys_id: str) -> tuple[str, str] | None:
|
||||
"""system_section before arcade boards: what the folders and the
|
||||
reviewed parents give."""
|
||||
own = _own_section(sys_id)
|
||||
own = own_section(sys_id)
|
||||
if own is not None:
|
||||
return _slug(own[0]), own[1]
|
||||
return manufacturer_slug(own[0]), own[1]
|
||||
parent = SYSTEM_PARENTS.get(sys_id)
|
||||
if parent is not None and parent in _section_pairs:
|
||||
return _slug(parent[0]), parent[1]
|
||||
if parent is not None and parent in section_pairs:
|
||||
return manufacturer_slug(parent[0]), parent[1]
|
||||
try:
|
||||
name = system_name(sys_id)
|
||||
except KeyError:
|
||||
return None
|
||||
places = _sections_by_name.get(name.casefold(), set())
|
||||
places = sections_by_name.get(name.casefold(), set())
|
||||
if len(places) != 1:
|
||||
return None
|
||||
mfr, console = next(iter(places))
|
||||
if mfr in _NAMELESS_TOPS or (
|
||||
mfr in _PROGRAM_TOPS and console.casefold() in _program_names
|
||||
mfr in PROGRAM_TOPS and console.casefold() in known_program_names
|
||||
):
|
||||
return None
|
||||
return _slug(mfr), console
|
||||
return manufacturer_slug(mfr), console
|
||||
|
||||
|
||||
def _system_link(sys_id: str, prefix: str = "") -> str:
|
||||
@@ -319,7 +319,7 @@ def set_arcade_boards(profiles: dict[str, dict], db: dict) -> None:
|
||||
"""Install the profiles and database the arcade boards are read from.
|
||||
Without it they are read from the repository on first use."""
|
||||
_arcade_source[0] = (profiles, db)
|
||||
_boards_built[0] = False
|
||||
boards_built[0] = False
|
||||
|
||||
|
||||
def _owner_ids(entry: dict, systems: list[str]) -> set[str]:
|
||||
@@ -379,16 +379,16 @@ def _arcade_suffix_sha1s(db: dict) -> frozenset[str]:
|
||||
|
||||
|
||||
def _build_boards() -> None:
|
||||
if _boards_built[0]:
|
||||
if boards_built[0]:
|
||||
return
|
||||
_ensure_console_sections()
|
||||
ensure_console_sections()
|
||||
source = _arcade_source[0]
|
||||
if source is None:
|
||||
source = _read_arcade_source()
|
||||
if source is None:
|
||||
_archive_boards.clear()
|
||||
_board_names.clear()
|
||||
_boards_built[0] = True
|
||||
boards_built[0] = True
|
||||
return
|
||||
_arcade_source[0] = source
|
||||
profiles, db = source
|
||||
@@ -413,7 +413,7 @@ def _build_boards() -> None:
|
||||
archives = _entry_archives(entry, files, by_name)
|
||||
_cast_votes(key, entry, owners, archives, votes, ids_by_name)
|
||||
_elect_boards(votes, ids_by_name, db)
|
||||
_boards_built[0] = True
|
||||
boards_built[0] = True
|
||||
|
||||
|
||||
def _read_arcade_source() -> tuple[dict, dict] | None:
|
||||
@@ -450,7 +450,7 @@ def _entry_archives(entry: dict, files: dict, by_name: dict) -> set[str]:
|
||||
if sha1 not in files:
|
||||
continue
|
||||
if crcs:
|
||||
held = zip_member_crcs(str(_REPO_ROOT / files[sha1]["path"]))
|
||||
held = zip_member_crcs(str(REPO_ROOT / files[sha1]["path"]))
|
||||
# An archive the build cannot read keeps its name.
|
||||
if held and not held & crcs:
|
||||
continue
|
||||
@@ -514,7 +514,7 @@ def _machine_section(sys_id: str) -> tuple[str, str] | None:
|
||||
of the folder holding it: an id with a section of its own keeps its
|
||||
archives where the collection files them."""
|
||||
parent = SYSTEM_PARENTS.get(sys_id)
|
||||
if parent is None or parent[0] == "Arcade" or parent not in _section_pairs:
|
||||
if parent is None or parent[0] == "Arcade" or parent not in section_pairs:
|
||||
return None
|
||||
return parent
|
||||
|
||||
@@ -589,7 +589,7 @@ def arcade_boards() -> dict[str, str]:
|
||||
return {board: system_name(board) for board in sorted(set(_board_names.values()))}
|
||||
|
||||
|
||||
def _field_text(key: object, value: object) -> str:
|
||||
def scalar_text(key: object, value: object) -> str:
|
||||
"""A scalar of a structured block. A source reference reads as code."""
|
||||
if isinstance(value, bool):
|
||||
text = "yes" if value else "no"
|
||||
@@ -611,9 +611,9 @@ def _field_label(key: object) -> str:
|
||||
FieldText = Callable[[object, object], str]
|
||||
|
||||
|
||||
def _render_yaml_value(
|
||||
def render_yaml_value(
|
||||
lines: list[str], val: object, indent: int = 4,
|
||||
field_text: FieldText = _field_text,
|
||||
field_text: FieldText = scalar_text,
|
||||
) -> None:
|
||||
"""Render any YAML value as a nested markdown list.
|
||||
|
||||
@@ -628,7 +628,7 @@ def _render_yaml_value(
|
||||
if isinstance(v, (dict, list)) and v:
|
||||
lines.append(f"{pad}- **{_field_label(k)}:**")
|
||||
lines.append("")
|
||||
_render_yaml_value(lines, v, indent + 4, field_text)
|
||||
render_yaml_value(lines, v, indent + 4, field_text)
|
||||
else:
|
||||
lines.append(f"{pad}- **{_field_label(k)}:** {field_text(k, v)}")
|
||||
lines.append("")
|
||||
@@ -645,7 +645,7 @@ def _render_yaml_value(
|
||||
lines.append(f"{pad}- {', '.join(parts)}".rstrip())
|
||||
if nested:
|
||||
lines.append("")
|
||||
_render_yaml_value(lines, nested, indent + 4, field_text)
|
||||
render_yaml_value(lines, nested, indent + 4, field_text)
|
||||
else:
|
||||
lines.append(f"{pad}- {field_text(None, item)}")
|
||||
lines.append("")
|
||||
@@ -659,11 +659,11 @@ def _platform_link(name: str, display: str, prefix: str = "") -> str:
|
||||
"""Generate a markdown link to a platform page."""
|
||||
return f"[{display}]({prefix}platforms/{name}.md)"
|
||||
|
||||
def _emulator_link(name: str, prefix: str = "") -> str:
|
||||
def emulator_link(name: str, prefix: str = "") -> str:
|
||||
"""Generate a markdown link to an emulator page."""
|
||||
return f"[{name}]({prefix}emulators/{name}.md)"
|
||||
|
||||
def _fmt_size(size: int) -> str:
|
||||
def fmt_size(size: int) -> str:
|
||||
if size >= 1024 * 1024 * 1024:
|
||||
return f"{size / (1024**3):.1f} GB"
|
||||
if size >= 1024 * 1024:
|
||||
@@ -672,12 +672,12 @@ def _fmt_size(size: int) -> str:
|
||||
return f"{size / 1024:.1f} KB"
|
||||
return f"{size} B"
|
||||
|
||||
def _pct(n: int, total: int) -> str:
|
||||
def percent_text(n: int, total: int) -> str:
|
||||
if total == 0:
|
||||
return "0%"
|
||||
return f"{n / total * 100:.1f}%"
|
||||
|
||||
def _by_mode(value: str | dict, mode: str) -> str:
|
||||
def by_mode(value: str | dict, mode: str) -> str:
|
||||
"""Read a profile field that may be keyed by build mode."""
|
||||
if isinstance(value, dict):
|
||||
return str(value.get(mode) or "") if mode else ""
|
||||
@@ -689,9 +689,6 @@ def _by_mode(value: str | dict, mode: str) -> str:
|
||||
_NAMELESS_TOPS = frozenset({"Other"})
|
||||
|
||||
|
||||
_REPO_ROOT = REPO_ROOT
|
||||
|
||||
|
||||
# A system id that names a family of arcade boards -> the board its link
|
||||
# leads to. RetroArch's sega-dreamcast-arcade lists the NAOMI, NAOMI 2 and
|
||||
# Atomiswave BIOS: the NAOMI page comes first, the Dreamcast section links
|
||||
|
||||
+20
-20
@@ -14,15 +14,15 @@ from pathlib import Path
|
||||
from core import upstream
|
||||
from core.paths import REPO_ROOT
|
||||
from model.sourceref import (
|
||||
_HEX_ADDRESS_RE,
|
||||
_prose_runs,
|
||||
HEX_ADDRESS_RE,
|
||||
prose_runs,
|
||||
is_binary_citation,
|
||||
ref_annotation,
|
||||
ref_role,
|
||||
source_ref_values,
|
||||
split_source_ref,
|
||||
)
|
||||
from sitegen.render import _by_mode, _escape_tags
|
||||
from sitegen.render import by_mode, escape_tags
|
||||
|
||||
|
||||
def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, str]]:
|
||||
@@ -44,8 +44,8 @@ def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, st
|
||||
return [
|
||||
(
|
||||
str(raw),
|
||||
_by_mode(pin_field, label),
|
||||
_by_mode(source_field, label),
|
||||
by_mode(pin_field, label),
|
||||
by_mode(source_field, label),
|
||||
)
|
||||
]
|
||||
|
||||
@@ -55,7 +55,7 @@ def _repo_pins(profile: dict, field: str, label: str) -> list[tuple[str, str, st
|
||||
key for key in raw if key != label
|
||||
]
|
||||
return [
|
||||
(str(raw[key]), _by_mode(pin_field, key), _by_mode(source_field, key))
|
||||
(str(raw[key]), by_mode(pin_field, key), by_mode(source_field, key))
|
||||
for key in ordered
|
||||
if raw.get(key)
|
||||
]
|
||||
@@ -70,7 +70,7 @@ _BROWSE_ONLY = {
|
||||
}
|
||||
|
||||
|
||||
def _browse_repo(url: str) -> upstream.Repo | None:
|
||||
def browse_repo(url: str) -> upstream.Repo | None:
|
||||
"""The repository a profile URL names, on any forge the pages can link.
|
||||
|
||||
Profiles pinned on SourceForge, voidpoint.io, Bitbucket or Software
|
||||
@@ -109,7 +109,7 @@ def _forge_sources(profile: dict, label: str = "") -> list[tuple[upstream.Repo,
|
||||
|
||||
for field in ("source", "upstream"):
|
||||
for value, pin, fallback in _repo_pins(profile, field, label):
|
||||
repo = _browse_repo(value)
|
||||
repo = browse_repo(value)
|
||||
if repo is None:
|
||||
continue
|
||||
repo_key = (repo.host, repo.slug)
|
||||
@@ -125,7 +125,7 @@ def _forge_sources(profile: dict, label: str = "") -> list[tuple[upstream.Repo,
|
||||
source_repos.add(repo_key)
|
||||
return candidates
|
||||
|
||||
def _source_permalink(repo: upstream.Repo, pin: str, path: str,
|
||||
def source_permalink(repo: upstream.Repo, pin: str, path: str,
|
||||
start: int | None, end: int | None) -> str:
|
||||
"""Forge-specific browser URL for one file at one immutable revision."""
|
||||
quoted_path = urllib.parse.quote(path, safe="/@:+-._~")
|
||||
@@ -256,7 +256,7 @@ def cited_paths(profile: dict) -> set[str]:
|
||||
for _label, refs in source_ref_values(value):
|
||||
paths.update(ref_role(part.path)[1] for part in split_source_ref(refs))
|
||||
elif isinstance(value, str) and ":" in value:
|
||||
for _n, _span, _spans, parts, _run, _wrapped in _prose_runs(value):
|
||||
for _n, _span, _spans, parts, _run, _wrapped in prose_runs(value):
|
||||
paths.update(part.path for part in parts)
|
||||
return {path for path in paths
|
||||
if _PATH_RE.fullmatch(path) and not is_binary_citation(path)}
|
||||
@@ -338,7 +338,7 @@ def build_files(profile: dict) -> list[tuple[upstream.Repo, str, str]]:
|
||||
revision, path). A tag can move, so a build read at a tag is not linked."""
|
||||
found = []
|
||||
for build in profile.get("pin_build") or []:
|
||||
repo = _browse_repo(str(build.get("repo", "")))
|
||||
repo = browse_repo(str(build.get("repo", "")))
|
||||
revision = str(build.get("revision", ""))
|
||||
if repo is not None and re.fullmatch(r"[0-9a-f]{40}", revision):
|
||||
found.append((repo, revision, str(build.get("path", ""))))
|
||||
@@ -392,14 +392,14 @@ def version_basis_url(profile: dict, basis: dict, mode: str = "") -> str:
|
||||
"""
|
||||
field = "upstream" if basis.get("repo") == "upstream" else "source"
|
||||
declared = next(iter(_repo_pins(profile, field, mode)), None)
|
||||
repo = _browse_repo(declared[0]) if declared else None
|
||||
repo = browse_repo(declared[0]) if declared else None
|
||||
if repo is None:
|
||||
return ""
|
||||
kind, path, tag = basis.get("kind"), str(basis.get("path") or ""), str(basis.get("tag") or "")
|
||||
if kind == "file" and path:
|
||||
pin = next((p for r, p in _forge_sources(profile, mode)
|
||||
if (r.host, r.slug) == (repo.host, repo.slug)), "")
|
||||
return _source_permalink(repo, pin, path, None, None) if pin and tree_holds(
|
||||
return source_permalink(repo, pin, path, None, None) if pin and tree_holds(
|
||||
repo, pin, path) else ""
|
||||
if kind == "tag" and tag and repo.family in ("github", "gitlab"):
|
||||
tree = "/-/tree/" if repo.family == "gitlab" else "/tree/"
|
||||
@@ -449,7 +449,7 @@ def role_sources(profile: dict, label: str = "") -> dict[str, tuple[upstream.Rep
|
||||
found: dict[str, tuple[upstream.Repo, str]] = {}
|
||||
for field in ("source", "upstream"):
|
||||
for value, pin, _fallback in _repo_pins(profile, field, label):
|
||||
repo = _browse_repo(value)
|
||||
repo = browse_repo(value)
|
||||
if repo is not None and pin and field not in found:
|
||||
found[field] = (repo, pin)
|
||||
return found
|
||||
@@ -475,7 +475,7 @@ def _two_repositories(profile: dict) -> bool:
|
||||
return bool(source and upstream_url and source != upstream_url)
|
||||
|
||||
|
||||
def _source_ref_markdown(profile: dict, value: str | dict | None) -> str:
|
||||
def source_ref_markdown(profile: dict, value: str | dict | None) -> str:
|
||||
"""Render source_ref values as pinned links when their forge is known.
|
||||
|
||||
Each part is followed by whose code it cites, in words, when the profile
|
||||
@@ -551,7 +551,7 @@ def source_ref_items(profile: dict, value: str | dict | None) -> list[tuple[str,
|
||||
rendered.append((f"`{display}`{note}", role))
|
||||
else:
|
||||
repo, pin = selected
|
||||
url = _source_permalink(
|
||||
url = source_permalink(
|
||||
repo, pin, real_path, part.start, part.end
|
||||
)
|
||||
rendered.append((f"[`{display}`]({url}){note}", role))
|
||||
@@ -568,7 +568,7 @@ def _annotation_markdown(text: str) -> str:
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
return " " + _escape_tags(re.sub(r"([*|\\])", r"\\\1", text))
|
||||
return " " + escape_tags(re.sub(r"([*|\\])", r"\\\1", text))
|
||||
|
||||
|
||||
def _binary_citation(path: str, previous: str) -> tuple[str, str]:
|
||||
@@ -578,7 +578,7 @@ def _binary_citation(path: str, previous: str) -> tuple[str, str]:
|
||||
ranges of one library: the bare address continues the binary before it.
|
||||
No revision of a repository holds those bytes, so nothing is linked.
|
||||
"""
|
||||
found = _HEX_ADDRESS_RE.search(path)
|
||||
found = HEX_ADDRESS_RE.search(path)
|
||||
if found is None:
|
||||
return f"`{path}`", path
|
||||
binary = path[:found.start()].rstrip(" :") or previous
|
||||
@@ -614,7 +614,7 @@ def link_prose_citations(profile: dict, text: str) -> str:
|
||||
for line in text.split("\n"):
|
||||
guarded = _guarded_spans(line)
|
||||
edits = []
|
||||
for _n, path_span, spans, parts, _run, wrapped in _prose_runs(line):
|
||||
for _n, path_span, spans, parts, _run, wrapped in prose_runs(line):
|
||||
path = parts[0].path
|
||||
if wrapped or " " in path or not _PATH_RE.fullmatch(path):
|
||||
continue
|
||||
@@ -631,7 +631,7 @@ def link_prose_citations(profile: dict, text: str) -> str:
|
||||
repo, pin = holders[0]
|
||||
for index, ((lo, hi), part) in enumerate(zip(spans, parts)):
|
||||
start = path_span[0] if index == 0 else lo
|
||||
url = _source_permalink(repo, pin, part.path, part.start, part.end)
|
||||
url = source_permalink(repo, pin, part.path, part.start, part.end)
|
||||
edits.append((start, hi, f"[`{line[start:hi]}`]({url})"))
|
||||
for start, end, link in sorted(edits, reverse=True):
|
||||
line = line[:start] + link + line[end:]
|
||||
|
||||
@@ -21,7 +21,7 @@ from html import unescape
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
from core.anchors import _unique, toc_slug
|
||||
from core.anchors import unique_anchor, toc_slug
|
||||
|
||||
BASE = "/retrobios/"
|
||||
SITE_URL = "https://abdess.github.io/retrobios/"
|
||||
@@ -145,14 +145,14 @@ def pin_heading_ids(text: str, title_id: str = "") -> str:
|
||||
tokens = attrs["attrs"].split() if attrs else []
|
||||
if any(token.startswith("#") for token in tokens):
|
||||
return match.group(0)
|
||||
ident = _unique(toc_slug(body), used)
|
||||
ident = unique_anchor(toc_slug(body), used)
|
||||
return f"{match['hashes']} {body.rstrip()} {{ {' '.join(['#' + ident, *tokens])} }}"
|
||||
|
||||
def raw(match: re.Match) -> str:
|
||||
if ID_ATTR.search(match["attrs"]):
|
||||
return match.group(0)
|
||||
level, text = match["level"], match["htmltext"]
|
||||
ident = _unique(toc_slug(text), used)
|
||||
ident = unique_anchor(toc_slug(text), used)
|
||||
return f'<h{level} id="{ident}"{match["attrs"]}>{text}</h{level}>'
|
||||
|
||||
def pick(match: re.Match) -> str:
|
||||
@@ -434,7 +434,7 @@ def page_aliases(rel: str) -> list[str]:
|
||||
from sitegen import render as siterender
|
||||
|
||||
by_page: dict[str, set[str]] = {}
|
||||
for sys_id in list(siterender._system_page_map):
|
||||
for sys_id in list(siterender.system_page_map):
|
||||
section = siterender.system_section(sys_id)
|
||||
names = siterender.system_search_aliases(sys_id)
|
||||
if not section or not names:
|
||||
@@ -444,7 +444,7 @@ def page_aliases(rel: str) -> list[str]:
|
||||
_page_aliases.clear()
|
||||
_page_aliases.update({page: sorted(names, key=str.casefold)
|
||||
for page, names in by_page.items()})
|
||||
_page_aliases_built[0] = bool(siterender._system_page_map)
|
||||
_page_aliases_built[0] = bool(siterender.system_page_map)
|
||||
return list(_page_aliases.get(rel, []))
|
||||
|
||||
|
||||
|
||||
@@ -9,26 +9,26 @@ from dataclasses import dataclass
|
||||
from model.collection import SECTION_LABELS
|
||||
from packs.crossref import FileConsumers
|
||||
from sitegen import markup
|
||||
from sitegen.cards import ROMSET_FAQ, _emulator_display, _romset_releases
|
||||
from sitegen.cards import ROMSET_FAQ, emulator_display, romset_releases
|
||||
from sitegen.consolecards import (
|
||||
Card,
|
||||
START_WITH_NAMES,
|
||||
_Item,
|
||||
_NO_PRIORITY,
|
||||
_add_name,
|
||||
_card_rank,
|
||||
_entries_by_section,
|
||||
_entry_systems,
|
||||
_reading_pairs,
|
||||
_region_order,
|
||||
_setup_name,
|
||||
_visible,
|
||||
_without_files,
|
||||
Item,
|
||||
NO_PRIORITY,
|
||||
add_name,
|
||||
card_rank,
|
||||
entries_by_section,
|
||||
entry_systems,
|
||||
reading_pairs,
|
||||
region_order,
|
||||
setup_name,
|
||||
visible_name,
|
||||
without_files,
|
||||
)
|
||||
from sitegen.descriptions import _said_as_list
|
||||
from sitegen.emulatorcards import _region_words
|
||||
from sitegen.descriptions import said_as_list
|
||||
from sitegen.emulatorcards import region_words
|
||||
from sitegen.install import comes_with_app
|
||||
from sitegen.render import _code, _count, console_anchor
|
||||
from sitegen.render import code_span, count_text, console_anchor
|
||||
|
||||
|
||||
class _StartGroup:
|
||||
@@ -63,13 +63,13 @@ class _StartGroup:
|
||||
self.extras: set[tuple[str, str]] = set()
|
||||
|
||||
def require(self, name: str, emulator: str) -> None:
|
||||
self.written.setdefault(_visible(name), name)
|
||||
self.requires.setdefault(_visible(name), set()).add(emulator)
|
||||
self.written.setdefault(visible_name(name), name)
|
||||
self.requires.setdefault(visible_name(name), set()).add(emulator)
|
||||
|
||||
def read_for(self, line: str, name: str, emulator: str, read: str, card: str) -> None:
|
||||
"""Record that ``emulator`` requires ``name`` for ``line``, under
|
||||
the name ``read``, its card titled ``card``."""
|
||||
visible = _visible(name)
|
||||
visible = visible_name(name)
|
||||
self.line_readers.setdefault(line, {}).setdefault(visible, set()).add(emulator)
|
||||
self.read_as.setdefault((line, visible, emulator), read)
|
||||
self.card_names.setdefault((line, visible), card)
|
||||
@@ -77,11 +77,11 @@ class _StartGroup:
|
||||
def absorb(self, other: _StartGroup) -> None:
|
||||
for region, names in other.by_region.items():
|
||||
for name in names:
|
||||
_add_name(self.by_region.setdefault(region, []), name)
|
||||
add_name(self.by_region.setdefault(region, []), name)
|
||||
for mine, theirs in ((self.plain, other.plain), (self.optional, other.optional),
|
||||
(self.extra, other.extra), (self.emulators, other.emulators)):
|
||||
for name in theirs:
|
||||
_add_name(mine, name)
|
||||
add_name(mine, name)
|
||||
for visible, emulators in other.requires.items():
|
||||
self.written.setdefault(visible, other.written[visible])
|
||||
self.requires.setdefault(visible, set()).update(emulators)
|
||||
@@ -112,13 +112,13 @@ class _StartGroup:
|
||||
continue
|
||||
reads = {self.read_as[(key, visible, e)] for e in emulators
|
||||
if (key, visible, e) in self.read_as}
|
||||
written = self.written.get(visible, _code(card))
|
||||
written = self.written.get(visible, code_span(card))
|
||||
# A linked name (a file under Arcade) keeps its link.
|
||||
shown = written if _visible(written) == card else _code(card)
|
||||
shown = written if visible_name(written) == card else code_span(card)
|
||||
if len(reads) == 1 and next(iter(reads)) != card:
|
||||
return f"{shown} (as {_code(next(iter(reads)))})"
|
||||
return f"{shown} (as {code_span(next(iter(reads)))})"
|
||||
return shown
|
||||
return self.written.get(visible, _code(visible))
|
||||
return self.written.get(visible, code_span(visible))
|
||||
|
||||
|
||||
_Read = tuple[str, dict, "str | None"]
|
||||
@@ -137,11 +137,11 @@ def _section_reads(
|
||||
kept: dict[str, list[_Read]] = {}
|
||||
for f in primaries:
|
||||
sha1 = str(f.get("sha1", ""))
|
||||
for emulator, entry in _reading_pairs(sha1, consumers):
|
||||
for emulator, entry in reading_pairs(sha1, consumers):
|
||||
if comes_with_app(entry):
|
||||
continue
|
||||
system = None
|
||||
systems = _entry_systems(emulator, entry)
|
||||
systems = entry_systems(emulator, entry)
|
||||
if here is not None and systems:
|
||||
system = next((s for s in systems if system_section(s) == here), None)
|
||||
if system is None:
|
||||
@@ -150,7 +150,7 @@ def _section_reads(
|
||||
candidates = list(primaries)
|
||||
known = (getattr(consumers, "_db", None) or {}).get("files", {})
|
||||
if here is not None:
|
||||
for sha1, emulator, entry, system in _entries_by_section(consumers).get(here, []):
|
||||
for sha1, emulator, entry, system in entries_by_section(consumers).get(here, []):
|
||||
record = known.get(sha1)
|
||||
parts = str((record or {}).get("path", "")).split("/")
|
||||
if (sha1 in held or not record or comes_with_app(entry) or ".variants" in parts
|
||||
@@ -173,14 +173,14 @@ class _SectionReads:
|
||||
for f in ranked:
|
||||
sha1 = str(f.get("sha1", ""))
|
||||
pairs = kept.get(sha1, [])
|
||||
name = _code(_setup_name(f, consumers, [(e, entry) for e, entry, _s in pairs]))
|
||||
name = code_span(setup_name(f, consumers, [(e, entry) for e, entry, _s in pairs]))
|
||||
if f.get("elsewhere"):
|
||||
name = f"[{name}]({markup.site_href(f'files/?sha1={sha1}')})"
|
||||
self.rendered[sha1] = name
|
||||
# A member read inside its archive is the archive's to name: FinalBurn
|
||||
# Neo reads sfix.sfix inside neogeo.zip, and the line had it read
|
||||
# sfix.sfix instead of neogeo.zip.
|
||||
self.archives = {_visible(name): (name, sha1)
|
||||
self.archives = {visible_name(name): (name, sha1)
|
||||
for sha1, name in reversed(self.rendered.items())}
|
||||
db = getattr(consumers, "_db", None) or {}
|
||||
self.known = db.get("files", {})
|
||||
@@ -195,8 +195,8 @@ class _SectionReads:
|
||||
found = [found] if isinstance(found, str) else sorted(found)
|
||||
found.sort(key=lambda s: "/.variants/" in str(self.known.get(s, {}).get("path", "")))
|
||||
if not found:
|
||||
return _code(archive), ""
|
||||
return f"[{_code(archive)}]({markup.site_href(f'files/?sha1={found[0]}')})", ""
|
||||
return code_span(archive), ""
|
||||
return f"[{code_span(archive)}]({markup.site_href(f'files/?sha1={found[0]}')})", ""
|
||||
|
||||
def reading(self, f: dict) -> Iterator[tuple[str, dict, str | None, str, str]]:
|
||||
"""Each read of a file: the emulator, its entry, the system, the
|
||||
@@ -223,7 +223,7 @@ def _weak_starts(ranked: list[dict], reads: _SectionReads) -> tuple[dict[str, se
|
||||
if entry.get("hle_fallback"):
|
||||
continue
|
||||
side = requiring if entry.get("required", True) else optional
|
||||
side.setdefault(named or _visible(name), set()).add(emulator)
|
||||
side.setdefault(named or visible_name(name), set()).add(emulator)
|
||||
needs_other = {emulator: {key for key, emulators in requiring.items() if emulator in emulators}
|
||||
for emulators in requiring.values() for emulator in emulators}
|
||||
weak = {key for key, emulators in requiring.items()
|
||||
@@ -251,10 +251,10 @@ def _chosen_members(ranked: list[dict], reads: _SectionReads,
|
||||
for emulator, entry, _system, name, named in reads.reading(f):
|
||||
place = _group_place(emulator, entry)
|
||||
if place is not None:
|
||||
member = named or _visible(name)
|
||||
member = named or visible_name(name)
|
||||
rank = (-len(requiring.get(member, ())),
|
||||
entry["priority"] if isinstance(entry.get("priority"), int) else _NO_PRIORITY,
|
||||
_visible(name))
|
||||
entry["priority"] if isinstance(entry.get("priority"), int) else NO_PRIORITY,
|
||||
visible_name(name))
|
||||
members.setdefault(place, []).append((rank, member))
|
||||
return {place: min(found)[1] for place, found in members.items()}
|
||||
|
||||
@@ -265,25 +265,25 @@ def _add_start_read(group: _StartGroup, f: dict, read_by: tuple[str, dict, str,
|
||||
emulator, its entry, the name the line writes and the card's sha1."""
|
||||
emulator, entry, name, named = read_by
|
||||
if named:
|
||||
group.sha1s.setdefault(_visible(name), named)
|
||||
group.sha1s.setdefault(visible_name(name), named)
|
||||
if emulator not in group.emulators:
|
||||
group.emulators.append(emulator)
|
||||
if entry.get("hle_fallback"):
|
||||
_add_name(group.optional, name)
|
||||
add_name(group.optional, name)
|
||||
group.hle.add(emulator)
|
||||
return
|
||||
if not entry.get("required", True):
|
||||
_add_name(group.extra, name)
|
||||
add_name(group.extra, name)
|
||||
return
|
||||
group.require(name, emulator)
|
||||
read = str(entry.get("archive") or entry.get("name") or _visible(name))
|
||||
read = str(entry.get("archive") or entry.get("name") or visible_name(name))
|
||||
card = str(entry["archive"]) if entry.get("archive") else str(f["name"])
|
||||
regions = sorted({str(r) for r in entry.get("region") or []})
|
||||
for region in regions or [""]:
|
||||
_add_name(group.by_region.setdefault(region, []) if region else group.plain, name)
|
||||
add_name(group.by_region.setdefault(region, []) if region else group.plain, name)
|
||||
group.read_for(region, name, emulator, read, card)
|
||||
if (named or _visible(name)) in weak:
|
||||
group.extras.add((region, _visible(name)))
|
||||
if (named or visible_name(name)) in weak:
|
||||
group.extras.add((region, visible_name(name)))
|
||||
|
||||
|
||||
def _start_groups(
|
||||
@@ -301,14 +301,14 @@ def _start_groups(
|
||||
the Mega CD BIOS for its Genesis), and one under Other is a single
|
||||
emulator's, its shaders and fonts. A file the emulator ships with is
|
||||
no file to fetch."""
|
||||
from model.systemnames import _heading_name, system_name
|
||||
from model.collection import _slug
|
||||
from model.systemnames import heading_name, system_name
|
||||
from model.collection import manufacturer_slug
|
||||
|
||||
here = (_slug(section[0]), section[1]) if section else None
|
||||
here = (manufacturer_slug(section[0]), section[1]) if section else None
|
||||
kept, candidates = _section_reads(files, consumers, here)
|
||||
|
||||
groups: dict[str | None, _StartGroup] = {}
|
||||
ranked = sorted(candidates, key=lambda f: _card_rank(f, consumers))
|
||||
ranked = sorted(candidates, key=lambda f: card_rank(f, consumers))
|
||||
reads = _SectionReads(kept, ranked, consumers)
|
||||
requiring, weak = _weak_starts(ranked, reads)
|
||||
chosen = _chosen_members(ranked, reads, requiring)
|
||||
@@ -316,7 +316,7 @@ def _start_groups(
|
||||
for f in ranked:
|
||||
for emulator, entry, system, name, named in reads.reading(f):
|
||||
place = _group_place(emulator, entry)
|
||||
if place is not None and chosen.get(place) != (named or _visible(name)):
|
||||
if place is not None and chosen.get(place) != (named or visible_name(name)):
|
||||
continue
|
||||
try:
|
||||
key = system_name(system) if system else None
|
||||
@@ -327,12 +327,12 @@ def _start_groups(
|
||||
named_keys = [key for key in groups if key is not None]
|
||||
if None in groups and named_keys:
|
||||
# An entry that names no system reads the section's own console.
|
||||
heading = _heading_name(*section) if section else None
|
||||
heading = heading_name(*section) if section else None
|
||||
groups[heading if heading in groups else named_keys[0]].absorb(groups.pop(None))
|
||||
return groups
|
||||
|
||||
|
||||
def _start_with(
|
||||
def start_with(
|
||||
files: list[dict], consumers: FileConsumers, first_below: bool = True,
|
||||
section: tuple[str, str] | None = None,
|
||||
) -> list[str]:
|
||||
@@ -350,7 +350,7 @@ def _start_with(
|
||||
return _start(files, consumers, first_below, section)[0]
|
||||
|
||||
|
||||
def _start_order(
|
||||
def start_order(
|
||||
files: list[dict], consumers: FileConsumers, section: tuple[str, str] | None = None,
|
||||
) -> list[str]:
|
||||
"""The sha1s of the files a section's start line names, in its order:
|
||||
@@ -372,7 +372,7 @@ def _start(
|
||||
lines = _lead_file(groups)
|
||||
if not lines:
|
||||
lines = _group_lines(groups, first_below, held, sha1s,
|
||||
_section_label(*section) if section and section != OTHER_ARCADE else "")
|
||||
section_label(*section) if section and section != OTHER_ARCADE else "")
|
||||
order: list[str] = []
|
||||
for line in lines:
|
||||
for visible in re.findall(r"`([^`]*)`", line):
|
||||
@@ -438,7 +438,7 @@ def _group_lines(
|
||||
|
||||
|
||||
def _display_names(emulators: set[str] | list[str]) -> list[str]:
|
||||
return sorted({_emulator_display(e) for e in emulators}, key=str.casefold)
|
||||
return sorted({emulator_display(e) for e in emulators}, key=str.casefold)
|
||||
|
||||
|
||||
def _names_counted(names: list[str], most: int = 3, noun: str = "") -> str:
|
||||
@@ -447,7 +447,7 @@ def _names_counted(names: list[str], most: int = 3, noun: str = "") -> str:
|
||||
if len(names) > most + 1:
|
||||
more = f"{len(names) - most} more" + (f" {noun}" if noun else "")
|
||||
return f"{', '.join(names[:most])} and {more}"
|
||||
return _said_as_list(names)
|
||||
return said_as_list(names)
|
||||
|
||||
|
||||
def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]:
|
||||
@@ -476,7 +476,7 @@ def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]:
|
||||
zipped = " Keep it zipped." if top.casefold().endswith(".zip") else ""
|
||||
names = _display_names(readers)
|
||||
said = (_names_counted(names, 2, "emulators") if len(names) > 2
|
||||
else _said_as_list(names))
|
||||
else said_as_list(names))
|
||||
lines = [f"**Start with** {written[top]}.{zipped} {said} read{'s' if len(names) == 1 else ''} it.",
|
||||
""]
|
||||
# The emulators that require other files and not this one, by the
|
||||
@@ -491,7 +491,7 @@ def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]:
|
||||
for files, who in sorted(others.items(), key=lambda item: (-len(item[1]), item[0])):
|
||||
names = _display_names(who)
|
||||
verb = "reads" if len(names) == 1 else "read"
|
||||
sentences.append(f"{_names_counted(names)} {verb} {_said_as_list(list(files))} instead.")
|
||||
sentences.append(f"{_names_counted(names)} {verb} {said_as_list(list(files))} instead.")
|
||||
if sentences:
|
||||
lines += [" ".join(sentences), ""]
|
||||
return lines
|
||||
@@ -510,7 +510,7 @@ class _GroupWords:
|
||||
return ", ".join(names)
|
||||
# The first three by rank, the rest counted: "the 9 files" named
|
||||
# none, and the Neo Geo BIOS everyone reads is filed under Arcade.
|
||||
return f"{', '.join(names[:3])} and {_count(len(names) - 3, 'more file')}" + (
|
||||
return f"{', '.join(names[:3])} and {count_text(len(names) - 3, 'more file')}" + (
|
||||
", first below" if below else "")
|
||||
|
||||
def instead_of(self, line: str, names: list[str], answered: set[str]) -> str:
|
||||
@@ -519,16 +519,16 @@ class _GroupWords:
|
||||
group = self.group
|
||||
readers = group.line_readers.get(line, {})
|
||||
others: dict[tuple[str, ...], set[str]] = {}
|
||||
for emulator in sorted(set().union(*(readers.get(_visible(n), set()) for n in names))
|
||||
for emulator in sorted(set().union(*(readers.get(visible_name(n), set()) for n in names))
|
||||
- answered):
|
||||
theirs = tuple(group.as_read(_visible(n), {emulator}, line) for n in names
|
||||
if emulator in readers.get(_visible(n), set()))
|
||||
theirs = tuple(group.as_read(visible_name(n), {emulator}, line) for n in names
|
||||
if emulator in readers.get(visible_name(n), set()))
|
||||
others.setdefault(theirs, set()).add(emulator)
|
||||
sentences = []
|
||||
for files, who in sorted(others.items(), key=lambda item: (-len(item[1]), item[0])):
|
||||
shown = _display_names(who)
|
||||
verb = "reads" if len(shown) == 1 else "read"
|
||||
sentences.append(f"{_names_counted(shown)} {verb} {_said_as_list(list(files))} instead.")
|
||||
sentences.append(f"{_names_counted(shown)} {verb} {said_as_list(list(files))} instead.")
|
||||
return " ".join(sentences)
|
||||
|
||||
def split(self, line: str, names: list[str]) -> tuple[list[str], str, set[str]]:
|
||||
@@ -538,13 +538,13 @@ class _GroupWords:
|
||||
for one slot: "fdsbios.zip, disksys.rom" read as two files to get."""
|
||||
group = self.group
|
||||
readers = group.line_readers.get(line, {})
|
||||
sets = {n: readers.get(_visible(n), set()) for n in names}
|
||||
sets = {n: readers.get(visible_name(n), set()) for n in names}
|
||||
lead = max(names, key=lambda n: len(sets[n]))
|
||||
main = [n for n in names if n == lead or sets[n] <= sets[lead]]
|
||||
rest = [n for n in names if n not in main]
|
||||
# A file the lead's readers require beside it is a start file too,
|
||||
# unless most of its readers take it as an extra.
|
||||
main = [n for n in main if n == lead or (line, _visible(n)) not in group.extras]
|
||||
main = [n for n in main if n == lead or (line, visible_name(n)) not in group.extras]
|
||||
return main, self.instead_of(line, rest, set(sets[lead])), set().union(*sets.values())
|
||||
|
||||
|
||||
@@ -577,14 +577,14 @@ def _runs_without(words: _GroupWords) -> list[tuple[str, str]]:
|
||||
def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str], set[str]]:
|
||||
"""The lines of the files picked by region, the emulators they answer
|
||||
and the names they give."""
|
||||
from model.region import _PARENT
|
||||
from model.region import PARENT
|
||||
|
||||
group = words.group
|
||||
order = _region_order()
|
||||
order = region_order()
|
||||
# A territory its region answers the same way adds nothing: Brazil
|
||||
# under Latin America.
|
||||
by_region = {r: names for r, names in group.by_region.items()
|
||||
if group.by_region.get(_PARENT.get(r, "")) != names}
|
||||
if group.by_region.get(PARENT.get(r, "")) != names}
|
||||
# Regions that need the same files share a line.
|
||||
regional: dict[tuple[str, ...], str] = {}
|
||||
answered: set[str] = set()
|
||||
@@ -592,7 +592,7 @@ def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str],
|
||||
for region in sorted(by_region, key=lambda r: (order.get(r, len(order)), r)):
|
||||
main, sentence, readers = words.split(region, by_region[region])
|
||||
answered |= readers
|
||||
shown |= {_visible(n) for n in by_region[region]}
|
||||
shown |= {visible_name(n) for n in by_region[region]}
|
||||
text = f"{words.listed(main)}. {sentence}" if sentence else words.listed(main)
|
||||
same = next((rs for rs, held in regional.items() if held == text), None)
|
||||
if same is None:
|
||||
@@ -600,7 +600,7 @@ def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str],
|
||||
else:
|
||||
regional[same + (region,)] = regional.pop(same)
|
||||
|
||||
out = [(", ".join(_region_words(r) for r in regions), regional[regions])
|
||||
out = [(", ".join(region_words(r) for r in regions), regional[regions])
|
||||
for regions in sorted(regional, key=lambda rs: (order.get(rs[0], len(order)), rs))]
|
||||
return out, answered, shown
|
||||
|
||||
@@ -613,10 +613,10 @@ def _plain_lines(words: _GroupWords, regional: bool, answered: set[str],
|
||||
# A name a region line gives already is no "also", and one only
|
||||
# emulators no region line answers reads is an "instead": armsx1 reads
|
||||
# scph1001.bin where the others pick a BIOS by region.
|
||||
plain = [n for n in group.plain if _visible(n) not in shown]
|
||||
plain = [n for n in group.plain if visible_name(n) not in shown]
|
||||
if plain and regional:
|
||||
readers = group.line_readers.get("", {})
|
||||
also = [n for n in plain if readers.get(_visible(n), set()) & answered]
|
||||
also = [n for n in plain if readers.get(visible_name(n), set()) & answered]
|
||||
if also:
|
||||
out.append(("", words.listed(also)))
|
||||
sentence = words.instead_of("", [n for n in plain if n not in also], answered)
|
||||
@@ -646,12 +646,12 @@ def _group_start(group: _StartGroup, first_below: bool) -> list[tuple[str, str]]
|
||||
out, answered, shown = _region_lines(words)
|
||||
out.extend(_plain_lines(words, bool(out), answered, shown))
|
||||
if not out and group.optional:
|
||||
out.append(("*", f"{_without_files(group.emulators)}. "
|
||||
out.append(("*", f"{without_files(group.emulators)}. "
|
||||
f"For full accuracy: {words.listed(group.optional)}."))
|
||||
elif not out and group.extra:
|
||||
# The Mega Drive's emulators read the TMSS BIOS when it is there:
|
||||
# the section said nothing under a home page saying none is needed.
|
||||
out.append(("*", f"{_without_files(group.emulators)}. "
|
||||
out.append(("*", f"{without_files(group.emulators)}. "
|
||||
f"Optional: {words.listed(group.extra, False)}."))
|
||||
return out
|
||||
|
||||
@@ -680,7 +680,7 @@ def _start_lines(block: list[tuple[str, str]], console: str = "") -> list[str]:
|
||||
return [*lines, ""]
|
||||
|
||||
|
||||
def _cards_markdown(cards: list[Card]) -> list[str]:
|
||||
def cards_markdown(cards: list[Card]) -> list[str]:
|
||||
"""Primaries, then the variants in a closed block."""
|
||||
lines = [line for variant, card, _sha1 in cards if not variant for line in card]
|
||||
variants = [card for variant, card, _sha1 in cards if variant]
|
||||
@@ -693,10 +693,10 @@ def _cards_markdown(cards: list[Card]) -> list[str]:
|
||||
return lines
|
||||
|
||||
|
||||
def _parts(cards: list[_Item], budget: int, sizes: list[int]) -> list[list[_Item]]:
|
||||
def card_runs(cards: list[Item], budget: int, sizes: list[int]) -> list[list[Item]]:
|
||||
"""Cards in runs of at most ``budget`` bytes, in order, ``sizes``
|
||||
giving each card's weight."""
|
||||
parts: list[list[_Item]] = [[]]
|
||||
parts: list[list[Item]] = [[]]
|
||||
size = 0
|
||||
for index, card in enumerate(cards):
|
||||
weight = sizes[index]
|
||||
@@ -708,7 +708,7 @@ def _parts(cards: list[_Item], budget: int, sizes: list[int]) -> list[list[_Item
|
||||
return parts
|
||||
|
||||
|
||||
def _console_heading(manufacturer: str, console: str, label: str = "") -> str:
|
||||
def console_heading(manufacturer: str, console: str, label: str = "") -> str:
|
||||
"""A console's heading, its name alone. An icon on 79 of 544 headings
|
||||
read as missing art on the rest, set the text at two positions on one
|
||||
page and faded out on one theme or the other. ``label`` is the text
|
||||
@@ -716,10 +716,10 @@ def _console_heading(manufacturer: str, console: str, label: str = "") -> str:
|
||||
return f"## {label or console} {{ #{console_anchor(manufacturer, console)} }}"
|
||||
|
||||
|
||||
def _romset_note(consoles: dict[str, list]) -> list[str]:
|
||||
def romset_note(consoles: dict[str, list]) -> list[str]:
|
||||
"""The line a page of MAME or FBNeo sets carries: an arcade player
|
||||
looking for the version found the answer only under Reference."""
|
||||
releases = _romset_releases()
|
||||
releases = romset_releases()
|
||||
if not any(str(f.get("name", "")) in releases for files in consoles.values() for f in files):
|
||||
return []
|
||||
return ["MAME and FBNeo sets must match the emulator's version. "
|
||||
@@ -732,7 +732,7 @@ OTHER_ARCADE = ("Arcade", "Arcade")
|
||||
OTHER_ARCADE_LABEL = "Other arcade files"
|
||||
|
||||
|
||||
def _section_label(manufacturer: str, console: str) -> str:
|
||||
def section_label(manufacturer: str, console: str) -> str:
|
||||
"""The heading a section shows."""
|
||||
if (manufacturer, console) == OTHER_ARCADE:
|
||||
return OTHER_ARCADE_LABEL
|
||||
|
||||
+35
-35
@@ -30,12 +30,12 @@ from sitegen.diagrams import (
|
||||
STROKE,
|
||||
TEXT_SIZE,
|
||||
WIDE,
|
||||
_badge,
|
||||
_badge_side,
|
||||
_line,
|
||||
_n,
|
||||
_rect,
|
||||
_text,
|
||||
badge,
|
||||
badge_side,
|
||||
svg_connector,
|
||||
svg_number,
|
||||
svg_rect,
|
||||
svg_text,
|
||||
diagram_files,
|
||||
pictures,
|
||||
svg_document,
|
||||
@@ -105,7 +105,7 @@ def description(tab: str) -> str:
|
||||
|
||||
|
||||
def _stroke(d: str, cls: str = "rb-d-line", width: float = 1.5) -> str:
|
||||
return f'<path d="{d}" fill="none" stroke="{STROKE}" stroke-width="{_n(width)}" class="{cls}"/>'
|
||||
return f'<path d="{d}" fill="none" stroke="{STROKE}" stroke-width="{svg_number(width)}" class="{cls}"/>'
|
||||
|
||||
|
||||
def _key_width(label: str) -> float:
|
||||
@@ -120,9 +120,9 @@ def _keys(x: float, y: float, w: float, word: str) -> list[str]:
|
||||
top = y + ICON_H / 2 - 12
|
||||
for label in labels:
|
||||
width = _key_width(label)
|
||||
out.append(_rect(left, top, width, 24, accent=True))
|
||||
out.append(svg_rect(left, top, width, 24, accent=True))
|
||||
out.append(
|
||||
f'<text x="{_n(left + width / 2)}" y="{_n(top + 16.5)}" font-size="{_n(KEY_SIZE)}" '
|
||||
f'<text x="{svg_number(left + width / 2)}" y="{svg_number(top + 16.5)}" font-size="{svg_number(KEY_SIZE)}" '
|
||||
f'text-anchor="middle" fill="currentColor" style="{MONO_STYLE}">{escape(label)}</text>')
|
||||
left += width + 4
|
||||
return out
|
||||
@@ -130,8 +130,8 @@ def _keys(x: float, y: float, w: float, word: str) -> list[str]:
|
||||
|
||||
def _menu(x: float, y: float, w: float) -> list[str]:
|
||||
cx, top = x + w / 2, y + 4
|
||||
out = [_rect(cx - 22, top, 44, 36)]
|
||||
out += [_stroke(f"M{_n(cx - 14)} {_n(top + 10 + 8 * i)} H{_n(cx + 14)}") for i in range(3)]
|
||||
out = [svg_rect(cx - 22, top, 44, 36)]
|
||||
out += [_stroke(f"M{svg_number(cx - 14)} {svg_number(top + 10 + 8 * i)} H{svg_number(cx + 14)}") for i in range(3)]
|
||||
return out
|
||||
|
||||
|
||||
@@ -139,11 +139,11 @@ def _search(x: float, y: float, w: float, word: str) -> list[str]:
|
||||
width = min(w - 4, len(word) * KEY_SIZE * 0.62 + 34)
|
||||
left, top = x + (w - width) / 2, y + ICON_H / 2 - 12
|
||||
return [
|
||||
_rect(left, top, width, 24, accent=True),
|
||||
f'<circle cx="{_n(left + 11)}" cy="{_n(top + 11)}" r="5" fill="none" stroke="{STROKE}" '
|
||||
svg_rect(left, top, width, 24, accent=True),
|
||||
f'<circle cx="{svg_number(left + 11)}" cy="{svg_number(top + 11)}" r="5" fill="none" stroke="{STROKE}" '
|
||||
'stroke-width="1.5" class="rb-d-line"/>',
|
||||
_stroke(f"M{_n(left + 15)} {_n(top + 15)} L{_n(left + 19)} {_n(top + 19)}"),
|
||||
f'<text x="{_n(left + 25)}" y="{_n(top + 16.5)}" font-size="{_n(KEY_SIZE)}" '
|
||||
_stroke(f"M{svg_number(left + 15)} {svg_number(top + 15)} L{svg_number(left + 19)} {svg_number(top + 19)}"),
|
||||
f'<text x="{svg_number(left + 25)}" y="{svg_number(top + 16.5)}" font-size="{svg_number(KEY_SIZE)}" '
|
||||
f'fill="currentColor" style="{MONO_STYLE}">{escape(word)}</text>',
|
||||
]
|
||||
|
||||
@@ -151,36 +151,36 @@ def _search(x: float, y: float, w: float, word: str) -> list[str]:
|
||||
def _window(x: float, y: float, w: float) -> list[str]:
|
||||
cx, top = x + w / 2, y + 2
|
||||
return [
|
||||
_rect(cx - 32, top, 64, 40),
|
||||
_stroke(f"M{_n(cx - 32)} {_n(top + 9)} H{_n(cx + 32)}"),
|
||||
f'<text x="{_n(cx - 24)}" y="{_n(top + 28)}" font-size="{_n(KEY_SIZE)}" '
|
||||
svg_rect(cx - 32, top, 64, 40),
|
||||
_stroke(f"M{svg_number(cx - 32)} {svg_number(top + 9)} H{svg_number(cx + 32)}"),
|
||||
f'<text x="{svg_number(cx - 24)}" y="{svg_number(top + 28)}" font-size="{svg_number(KEY_SIZE)}" '
|
||||
f'fill="currentColor" style="{MONO_STYLE}">>_</text>',
|
||||
]
|
||||
|
||||
|
||||
def _copy(x: float, y: float, w: float) -> list[str]:
|
||||
cx, top = x + w / 2, y + 6
|
||||
return [_rect(cx - 12, top, 18, 24), _rect(cx - 6, top + 7, 18, 24, accent=True)]
|
||||
return [svg_rect(cx - 12, top, 18, 24), svg_rect(cx - 6, top + 7, 18, 24, accent=True)]
|
||||
|
||||
|
||||
def _mouse(x: float, y: float, w: float) -> list[str]:
|
||||
cx, top = x + w / 2, y + 2
|
||||
return [
|
||||
f'<rect x="{_n(cx - 13)}" y="{_n(top)}" width="26" height="40" rx="12" fill="none" '
|
||||
f'<rect x="{svg_number(cx - 13)}" y="{svg_number(top)}" width="26" height="40" rx="12" fill="none" '
|
||||
f'stroke="{STROKE}" stroke-width="1.5" class="rb-d-line"/>',
|
||||
# The right button, the one to press.
|
||||
f'<path d="M{_n(cx + 1)} {_n(top + 1)} A12 12 0 0 1 {_n(cx + 12)} {_n(top + 13)} '
|
||||
f'L{_n(cx + 1)} {_n(top + 13)} Z" fill="currentColor" class="rb-d-num"/>',
|
||||
_stroke(f"M{_n(cx)} {_n(top)} V{_n(top + 14)} M{_n(cx - 13)} {_n(top + 14)} "
|
||||
f"H{_n(cx + 13)}"),
|
||||
f'<path d="M{svg_number(cx + 1)} {svg_number(top + 1)} A12 12 0 0 1 {svg_number(cx + 12)} {svg_number(top + 13)} '
|
||||
f'L{svg_number(cx + 1)} {svg_number(top + 13)} Z" fill="currentColor" class="rb-d-num"/>',
|
||||
_stroke(f"M{svg_number(cx)} {svg_number(top)} V{svg_number(top + 14)} M{svg_number(cx - 13)} {svg_number(top + 14)} "
|
||||
f"H{svg_number(cx + 13)}"),
|
||||
]
|
||||
|
||||
|
||||
def _power(x: float, y: float, w: float) -> list[str]:
|
||||
cx, cy = x + w / 2, y + ICON_H / 2 + 2
|
||||
return [
|
||||
_stroke(f"M{_n(cx - 9)} {_n(cy - 11)} A14 14 0 1 0 {_n(cx + 9)} {_n(cy - 11)}", width=2.5),
|
||||
_stroke(f"M{_n(cx)} {_n(cy - 18)} V{_n(cy - 2)}", width=2.5),
|
||||
_stroke(f"M{svg_number(cx - 9)} {svg_number(cy - 11)} A14 14 0 1 0 {svg_number(cx + 9)} {svg_number(cy - 11)}", width=2.5),
|
||||
_stroke(f"M{svg_number(cx)} {svg_number(cy - 18)} V{svg_number(cy - 2)}", width=2.5),
|
||||
]
|
||||
|
||||
|
||||
@@ -202,34 +202,34 @@ def _wide(steps: tuple[Step, ...]) -> tuple[float, float, list[str]]:
|
||||
out: list[str] = []
|
||||
for index, (step, lines) in enumerate(zip(steps, captions)):
|
||||
x = 1 + index * (width + gap)
|
||||
out.append(_rect(x, 1, width, height))
|
||||
out += _badge(x + 8, 8, str(index + 1))
|
||||
out.append(svg_rect(x, 1, width, height))
|
||||
out += badge(x + 8, 8, str(index + 1))
|
||||
out += _icon(step, x + 4, 30, width - 8)
|
||||
y = 30 + ICON_H + 24
|
||||
for line in lines:
|
||||
out.append(_text(x + width / 2, y, line, anchor="middle"))
|
||||
out.append(svg_text(x + width / 2, y, line, anchor="middle"))
|
||||
y += 18
|
||||
if index < len(steps) - 1:
|
||||
mid = 1 + height / 2
|
||||
out += _line([(x + width + 1, mid), (x + width + gap - 1, mid)])
|
||||
out += svg_connector([(x + width + 1, mid), (x + width + gap - 1, mid)])
|
||||
return WIDE, height + 2, out
|
||||
|
||||
|
||||
def _narrow(steps: tuple[Step, ...]) -> tuple[float, float, list[str]]:
|
||||
"""One card a row: number, pictogram, caption."""
|
||||
icon_w, row_gap = 112.0, 8.0
|
||||
text_x = 8 + _badge_side("9") + 6 + icon_w + 8
|
||||
text_x = 8 + badge_side("9") + 6 + icon_w + 8
|
||||
out: list[str] = []
|
||||
y = 1.0
|
||||
for index, step in enumerate(steps):
|
||||
lines = wrap(step.caption, NARROW - text_x - 8, TEXT_SIZE)
|
||||
height = max(ICON_H + 12, len(lines) * 18 + 16)
|
||||
out.append(_rect(1, y, NARROW - 2, height))
|
||||
out += _badge(8, y + height / 2 - 10, str(index + 1))
|
||||
out += _icon(step, 8 + _badge_side("9") + 6, y + (height - ICON_H) / 2, icon_w)
|
||||
out.append(svg_rect(1, y, NARROW - 2, height))
|
||||
out += badge(8, y + height / 2 - 10, str(index + 1))
|
||||
out += _icon(step, 8 + badge_side("9") + 6, y + (height - ICON_H) / 2, icon_w)
|
||||
ty = y + height / 2 - (len(lines) - 1) * 9 + 5
|
||||
for line in lines:
|
||||
out.append(_text(text_x, ty, line))
|
||||
out.append(svg_text(text_x, ty, line))
|
||||
ty += 18
|
||||
y += height + row_gap
|
||||
return NARROW, y - row_gap + 1, out
|
||||
|
||||
@@ -11,12 +11,13 @@ from model.collection import collection_paths
|
||||
from model.systemnames import system_name
|
||||
from sitegen import starlight as sitestarlight
|
||||
from sitegen.cards import emulator_file_anchors
|
||||
from sitegen.config import REPO_URL, SITE_NAME, SITE_URL, _REPO_ROOT
|
||||
from sitegen.config import REPO_URL, SITE_NAME, SITE_URL
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.descriptions import EMULATOR_SNIPPETS, NOTHING_TO_FETCH, PAGE_DATA
|
||||
from sitegen.emulatorcards import _snippet_noun
|
||||
from sitegen.emulatorcards import snippet_noun
|
||||
from sitegen.install import comes_with_app
|
||||
from sitegen.lookup import _data_member_digests, _hash_values
|
||||
from sitegen.render import _system_page_map
|
||||
from sitegen.lookup import data_member_digests, sorted_hash_values
|
||||
from sitegen.render import system_page_map
|
||||
from sitegen.write import write_if_changed
|
||||
|
||||
|
||||
@@ -50,12 +51,12 @@ def collection_dat(db: dict, generated_at: str) -> str:
|
||||
games, generated_at)
|
||||
|
||||
|
||||
def _write_platform_dats(folder: Path, db: dict, members: dict, generated_at: str) -> list[Path]:
|
||||
def write_platform_dats(folder: Path, db: dict, members: dict, generated_at: str) -> list[Path]:
|
||||
"""downloads/dat/<platform>.dat for each install manifest."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
digests = _data_member_digests(members)
|
||||
digests = data_member_digests(members)
|
||||
written = []
|
||||
for source in sorted((_REPO_ROOT / "install").glob("*.json")):
|
||||
for source in sorted((REPO_ROOT / "install").glob("*.json")):
|
||||
manifest = json.loads(source.read_text(encoding="utf-8"))
|
||||
path = folder / f"{source.stem}.dat"
|
||||
write_if_changed(str(path), platform_dat(manifest, db, digests, generated_at))
|
||||
@@ -197,7 +198,7 @@ def platform_structured_data(name: str, coverage: dict) -> dict:
|
||||
identifiers = [
|
||||
f"{field}:{value}"
|
||||
for field in ("sha1", "md5", "crc32", "sha256")
|
||||
for value in _hash_values(entry.get(field))
|
||||
for value in sorted_hash_values(entry.get(field))
|
||||
]
|
||||
if identifiers:
|
||||
part["identifier"] = identifiers
|
||||
@@ -302,7 +303,7 @@ def record_emulator_page(name: str, profile: dict) -> None:
|
||||
fetched = [f for f in listed if f.get("name") and not comes_with_app(f)]
|
||||
systems = profile.get("systems") or []
|
||||
first = systems[0] if systems else ""
|
||||
makers = [_system_page_map[sys_id][0] for sys_id in systems if sys_id in _system_page_map]
|
||||
makers = [system_page_map[sys_id][0] for sys_id in systems if sys_id in system_page_map]
|
||||
if makers:
|
||||
sitestarlight.EMULATOR_CARDS[f"emulators/{name}"] = makers[0]
|
||||
else:
|
||||
@@ -320,7 +321,7 @@ def record_emulator_page(name: str, profile: dict) -> None:
|
||||
system_name(first) if 0 < len(systems) <= 5 else "",
|
||||
list(names.values()),
|
||||
len({Path(str(f["name"])).name.casefold() for f in fetched if f.get("required") is True}),
|
||||
_snippet_noun(names.values(), len(firmware), len(fetched)),
|
||||
snippet_noun(names.values(), len(firmware), len(fetched)),
|
||||
)
|
||||
if listed and all(comes_with_app(f) for f in listed):
|
||||
NOTHING_TO_FETCH.add(key)
|
||||
@@ -370,7 +371,7 @@ def emulator_structured_data(profile: dict) -> dict:
|
||||
identifiers = [
|
||||
f"{field}:{value}"
|
||||
for field in ("sha1", "sha256", "md5", "crc32")
|
||||
for value in _hash_values(f.get(field))
|
||||
for value in sorted_hash_values(f.get(field))
|
||||
]
|
||||
part: dict[str, object] = {
|
||||
"@type": "CreativeWork",
|
||||
@@ -389,7 +390,7 @@ def emulator_structured_data(profile: dict) -> dict:
|
||||
"identifier": [
|
||||
f"{field}:{value}"
|
||||
for field in ("sha1", "crc32")
|
||||
for value in _hash_values(member.get(field))
|
||||
for value in sorted_hash_values(member.get(field))
|
||||
],
|
||||
}
|
||||
for member in f.get("contents") or []
|
||||
|
||||
@@ -10,12 +10,13 @@ import re
|
||||
import urllib.parse
|
||||
from dataclasses import dataclass
|
||||
|
||||
from model.collection import SECTION_LABELS, _slug
|
||||
from model.collection import SECTION_LABELS, manufacturer_slug
|
||||
from model.composition import GAME_DATA_TOPS
|
||||
from packs.crossref import FileConsumers
|
||||
from sitegen import markup
|
||||
from sitegen.cards import _icon_symbol
|
||||
from sitegen.config import _REPO_ROOT, _date_line
|
||||
from sitegen.cards import icon_symbol
|
||||
from sitegen.config import date_line
|
||||
from core.paths import REPO_ROOT
|
||||
from sitegen.consolecards import (
|
||||
CARD_HTML_RATIO,
|
||||
CONSOLE_PAGES,
|
||||
@@ -23,26 +24,26 @@ from sitegen.consolecards import (
|
||||
INSTALL_HTML_RATIO,
|
||||
SYSTEM_PAGE_BUDGET,
|
||||
SYSTEM_SUMMARY_HTML,
|
||||
_console_cards,
|
||||
_install_box_weight,
|
||||
console_cards,
|
||||
install_box_weight,
|
||||
)
|
||||
from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT
|
||||
from sitegen.fields import search_excluded
|
||||
from sitegen.home import _next_block
|
||||
from sitegen.install import _console_install_block, _platform_display
|
||||
from sitegen.parts import _parent_front_matter
|
||||
from sitegen.render import _count, _slugify_anchor, console_href, record_console_pages
|
||||
from sitegen.home import next_block
|
||||
from sitegen.install import console_install_block, platform_display
|
||||
from sitegen.parts import parent_front_matter
|
||||
from sitegen.render import count_text, slugify_anchor, console_href, record_console_pages
|
||||
from sitegen.startwith import (
|
||||
OTHER_ARCADE,
|
||||
_cards_markdown,
|
||||
_console_heading,
|
||||
_parts,
|
||||
_romset_note,
|
||||
_section_label,
|
||||
_start_order,
|
||||
_start_with,
|
||||
cards_markdown,
|
||||
console_heading,
|
||||
card_runs,
|
||||
romset_note,
|
||||
section_label,
|
||||
start_order,
|
||||
start_with,
|
||||
)
|
||||
from sitegen.systemsindex import _folder_emulator
|
||||
from sitegen.systemsindex import folder_emulator
|
||||
|
||||
|
||||
_NEXT_FROM_SYSTEMS = [
|
||||
@@ -227,7 +228,7 @@ def _system_front_matter(
|
||||
"""The front matter of a system page: the page it belongs to, the
|
||||
parts before and after it (label, site path), its search weight and
|
||||
the consoles it holds, which the search reads as a field."""
|
||||
lines = _parent_front_matter(parent)
|
||||
lines = parent_front_matter(parent)
|
||||
for key, link in (("prev", prev), ("next", following)):
|
||||
if link:
|
||||
lines += [f"{key}:", f" label: {json.dumps(link[0])}", f" link: {json.dumps(link[1])}"]
|
||||
@@ -247,7 +248,7 @@ def _part_weight() -> float:
|
||||
def _manifest_systems(platform: str) -> frozenset[str]:
|
||||
"""The system ids a platform's install manifest records: --system
|
||||
refuses any other."""
|
||||
manifest = _REPO_ROOT / "install" / f"{platform}.json"
|
||||
manifest = REPO_ROOT / "install" / f"{platform}.json"
|
||||
if not manifest.is_file():
|
||||
return frozenset()
|
||||
document = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
@@ -274,7 +275,7 @@ def _install_pairs(
|
||||
if recorded:
|
||||
pairs.append((platform, recorded[0]))
|
||||
have.add(platform)
|
||||
return sorted(pairs, key=lambda pair: (_platform_display(pair[0]).casefold(), pair[1]))
|
||||
return sorted(pairs, key=lambda pair: (platform_display(pair[0]).casefold(), pair[1]))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -313,7 +314,7 @@ class _MakerPages:
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
manufacturer, consoles = self.manufacturer, self.consoles
|
||||
self.slug = _slug(manufacturer)
|
||||
self.slug = manufacturer_slug(manufacturer)
|
||||
self.boards = {console: _BOARD_CONSOLES[console] for console in consoles
|
||||
if manufacturer == "Arcade" and console in _BOARD_CONSOLES}
|
||||
self.json_next = (f"[Every hash of these files, as JSON](../api/v1/systems/"
|
||||
@@ -324,7 +325,7 @@ class _MakerPages:
|
||||
boards = self.boards
|
||||
self.ordered = sorted(consoles, key=lambda c: (bool(boards) and c not in boards, c))
|
||||
self.starts = {console: [] if boards and console not in boards
|
||||
else _start_order(consoles[console], self.consumers, (manufacturer, console))
|
||||
else start_order(consoles[console], self.consumers, (manufacturer, console))
|
||||
for console in consoles}
|
||||
# One line, then the legend closed: four paragraphs said the same on
|
||||
# every maker's page before its first console.
|
||||
@@ -350,18 +351,18 @@ class _MakerPages:
|
||||
def start_of(self, console: str, first_below: bool = True) -> list[str]:
|
||||
if self.boards and console not in self.boards:
|
||||
return []
|
||||
return [*_start_with(self.consoles[console], self.consumers, first_below,
|
||||
return [*start_with(self.consoles[console], self.consumers, first_below,
|
||||
(self.manufacturer, console)),
|
||||
*_boards_line(self.manufacturer, console)]
|
||||
|
||||
def cards_of(self, console: str, anchors: set[str], by_name: bool = False) -> list[Card]:
|
||||
return _console_cards(self.manufacturer, self.consoles[console], self.consumers, anchors,
|
||||
return console_cards(self.manufacturer, self.consoles[console], self.consumers, anchors,
|
||||
by_name, self.starts[console])
|
||||
|
||||
def install_block(self, console: str) -> list[str]:
|
||||
lead = self.starts[console][0] if self.starts[console] else None
|
||||
return _console_install_block(
|
||||
_section_label(self.manufacturer, console),
|
||||
return console_install_block(
|
||||
section_label(self.manufacturer, console),
|
||||
_install_pairs(self.installs.get(console, []), lead, self.consumers))
|
||||
|
||||
def all_sections(self) -> dict[str, list[Card]]:
|
||||
@@ -370,28 +371,28 @@ class _MakerPages:
|
||||
|
||||
def consoles_front(self, kept: set[str] | None = None) -> list[str]:
|
||||
return _system_front_matter(consoles=[
|
||||
_section_label(self.manufacturer, c) for c in self.machines
|
||||
section_label(self.manufacturer, c) for c in self.machines
|
||||
if kept is None or c in kept])
|
||||
|
||||
def head(self, front: list[str]) -> list[str]:
|
||||
"""A maker's page down to its first console."""
|
||||
return [
|
||||
*front, f"# {self.manufacturer}", "", self.intro, "", *self.legend,
|
||||
*_romset_note(self.consoles), *_icon_symbol(),
|
||||
*romset_note(self.consoles), *icon_symbol(),
|
||||
]
|
||||
|
||||
def whole_page(self, sections: dict[str, list[Card]]) -> str:
|
||||
lines = self.head(self.front)
|
||||
for console, cards in sections.items():
|
||||
lines.append(_console_heading(self.manufacturer, console,
|
||||
_section_label(self.manufacturer, console)))
|
||||
lines.append(console_heading(self.manufacturer, console,
|
||||
section_label(self.manufacturer, console)))
|
||||
lines.append("")
|
||||
lines.extend(self.start_of(console))
|
||||
lines.extend(self.install_block(console))
|
||||
lines.extend(_cards_markdown(cards))
|
||||
lines.extend(cards_markdown(cards))
|
||||
lines.append("")
|
||||
lines.extend(_next_block([*_NEXT_FROM_SYSTEMS, self.json_next]))
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(next_block([*_NEXT_FROM_SYSTEMS, self.json_next]))
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
def cut(self, console: str, by_name: bool) -> list[list[Card]]:
|
||||
@@ -402,16 +403,16 @@ class _MakerPages:
|
||||
with markup.using("mkdocs"):
|
||||
sizes = [_card_weight(card) for _variant, card, _sha1 in self.cards_of(
|
||||
console, set(), by_name)]
|
||||
parts = _parts(cards, self.budget, sizes)
|
||||
parts = card_runs(cards, self.budget, sizes)
|
||||
if len(parts) < 2:
|
||||
return parts
|
||||
# Even parts: cut at budget, the PlayStation 2 was 137 cards
|
||||
# and 4. The same number of parts, each near the mean.
|
||||
share = -(-sum(sizes) // len(parts))
|
||||
even = _parts(cards, share, sizes)
|
||||
even = card_runs(cards, share, sizes)
|
||||
while len(even) > len(parts):
|
||||
share += max(1, share // 50)
|
||||
even = _parts(cards, share, sizes)
|
||||
even = card_runs(cards, share, sizes)
|
||||
return even
|
||||
|
||||
def moved(self, weights: dict[str, int], rendered: dict[str, float]) -> set[str]:
|
||||
@@ -445,7 +446,7 @@ class _MakerPages:
|
||||
weight=_part_weight() if len(stems) > 1 else None,
|
||||
consoles=[label] if index == 0 and console in self.machines else None),
|
||||
# The crumbs end on the maker's page: no line says it again.
|
||||
f"# {plan.titles[index]}", "", *_icon_symbol(),
|
||||
f"# {plan.titles[index]}", "", *icon_symbol(),
|
||||
]
|
||||
if len(stems) > 1:
|
||||
others = ", ".join(
|
||||
@@ -458,14 +459,14 @@ class _MakerPages:
|
||||
if index == 0:
|
||||
lines.extend(self.start_of(console, len(stems) == 1))
|
||||
lines.extend(self.legend)
|
||||
lines.extend(_romset_note({console: self.consoles[console]}))
|
||||
lines.extend(romset_note({console: self.consoles[console]}))
|
||||
lines.extend(self.install_block(console))
|
||||
lines.extend(["## Files", ""])
|
||||
lines.extend(_cards_markdown(part))
|
||||
lines.extend(cards_markdown(part))
|
||||
lines.append("")
|
||||
lines.extend(_next_block([f"[{self.manufacturer}]({self.slug}.md), every section"]
|
||||
lines.extend(next_block([f"[{self.manufacturer}]({self.slug}.md), every section"]
|
||||
+ _NEXT_FROM_SYSTEMS + [self.json_next]))
|
||||
lines.extend(["", _date_line()])
|
||||
lines.extend(["", date_line()])
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
def moved_section(self, console: str, pages: dict[str, tuple[str, dict[str, list]]]) -> list[str]:
|
||||
@@ -474,7 +475,7 @@ class _MakerPages:
|
||||
from sitegen.render import board_slug
|
||||
|
||||
manufacturer = self.manufacturer
|
||||
label = _section_label(manufacturer, console)
|
||||
label = section_label(manufacturer, console)
|
||||
# One page keeps the required files first. Parts are named by their
|
||||
# first and last file, so a console cut in parts goes by name, the
|
||||
# files the start line names first.
|
||||
@@ -483,7 +484,7 @@ class _MakerPages:
|
||||
parts = self.cut(console, True)
|
||||
board = self.boards.get(console)
|
||||
base = (f"arcade-{board_slug(board)}" if board
|
||||
else f"{self.slug}-{_slugify_anchor(console) or 'files'}")
|
||||
else f"{self.slug}-{slugify_anchor(console) or 'files'}")
|
||||
stems = [base if index == 0 else f"{base}-{index + 1}" for index in range(len(parts))]
|
||||
clash = set(stems) & set(pages)
|
||||
if clash:
|
||||
@@ -495,12 +496,12 @@ class _MakerPages:
|
||||
# A part by the files it holds: "Arcade: Arcade, part 3 of 5" said
|
||||
# nothing a search result could use. A folder under Other goes by
|
||||
# its emulator's name: "mame files" named the folder.
|
||||
named = _folder_emulator(console)[0] if manufacturer == "Other" else None
|
||||
named = folder_emulator(console)[0] if manufacturer == "Other" else None
|
||||
titles = ([f"{manufacturer}: {named or label}"] if len(stems) == 1 else [
|
||||
"{} files {} to {}".format(named or _part_name(manufacturer, console),
|
||||
*_part_ends(part, lead))
|
||||
for part in parts])
|
||||
count = _count(len(self.consoles[console]), "file")
|
||||
count = count_text(len(self.consoles[console]), "file")
|
||||
summary = list(self.start_of(console, False))
|
||||
if len(stems) == 1:
|
||||
own = "its" if len(self.consoles[console]) == 1 else "their"
|
||||
@@ -555,7 +556,7 @@ def system_pages(
|
||||
# page, which the card weights never counted. A page is also cut when
|
||||
# its estimate as it renders passes the summary's.
|
||||
with markup.using("mkdocs"):
|
||||
boxes = {console: _install_box_weight(maker.install_block(console)) for console in consoles}
|
||||
boxes = {console: install_box_weight(maker.install_block(console)) for console in consoles}
|
||||
rendered = {console: CARD_HTML_RATIO * weights[console] + INSTALL_HTML_RATIO * boxes[console]
|
||||
for console in weights}
|
||||
if (not maker.boards and manufacturer not in CONSOLE_PAGES and len(measured_text) <= budget
|
||||
@@ -568,18 +569,18 @@ def system_pages(
|
||||
summary = maker.head(maker.consoles_front(set(consoles) - moved))
|
||||
summary_anchors: set[str] = set()
|
||||
for console in maker.ordered:
|
||||
label = _section_label(manufacturer, console)
|
||||
summary.append(_console_heading(manufacturer, console, label))
|
||||
label = section_label(manufacturer, console)
|
||||
summary.append(console_heading(manufacturer, console, label))
|
||||
summary.append("")
|
||||
if console not in moved:
|
||||
summary.extend(maker.start_of(console))
|
||||
summary.extend(maker.install_block(console))
|
||||
summary.extend(_cards_markdown(maker.cards_of(console, summary_anchors)))
|
||||
summary.extend(cards_markdown(maker.cards_of(console, summary_anchors)))
|
||||
summary.append("")
|
||||
continue
|
||||
summary.extend(maker.moved_section(console, pages))
|
||||
summary.extend(_next_block([*_NEXT_FROM_SYSTEMS, maker.json_next]))
|
||||
summary.extend(["", _date_line()])
|
||||
summary.extend(next_block([*_NEXT_FROM_SYSTEMS, maker.json_next]))
|
||||
summary.extend(["", date_line()])
|
||||
kept = {console: files for console, files in consoles.items() if console not in moved}
|
||||
return {slug: ("\n".join(summary) + "\n", kept), **pages}
|
||||
|
||||
@@ -604,7 +605,7 @@ def _part_range(part: list[Card], lead: set[str] | frozenset[str] = frozenset())
|
||||
first, last = _part_ends(part, lead)
|
||||
if len(part) == 1:
|
||||
return f"`{first}`"
|
||||
return f"{_count(len(part), 'file')}, `{first}` to `{last}`"
|
||||
return f"{count_text(len(part), 'file')}, `{first}` to `{last}`"
|
||||
|
||||
|
||||
def generate_system_page(
|
||||
@@ -619,4 +620,4 @@ def generate_system_page(
|
||||
install command the section offers. A page over the budget is the
|
||||
summary system_pages writes, its consoles on pages of their own.
|
||||
"""
|
||||
return system_pages(manufacturer, consoles, consumers, installs)[_slug(manufacturer)][0]
|
||||
return system_pages(manufacturer, consoles, consumers, installs)[manufacturer_slug(manufacturer)][0]
|
||||
@@ -2,21 +2,21 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from model.collection import SECTION_LABELS, _profiles_on_disk, _slug
|
||||
from model.collection import SECTION_LABELS, profiles_on_disk, manufacturer_slug
|
||||
from model.composition import GAME_DATA_TOPS
|
||||
from sitegen import starlight as sitestarlight
|
||||
from sitegen.render import _count, console_href
|
||||
from sitegen.startwith import _section_label
|
||||
from sitegen.render import count_text, console_href
|
||||
from sitegen.startwith import section_label
|
||||
|
||||
|
||||
def _console_display(manufacturer: str, console: str) -> str:
|
||||
"""A console section's name as the reader looks for it: the heading
|
||||
system_name gives its id, or the folder alone under a program's top
|
||||
(Other, Arcade), where "Other mame" would name nothing."""
|
||||
from model.collection import _PROGRAM_TOPS
|
||||
from model.systemnames import _heading_name
|
||||
from model.collection import PROGRAM_TOPS
|
||||
from model.systemnames import heading_name
|
||||
|
||||
return console if manufacturer in _PROGRAM_TOPS else _heading_name(manufacturer, console)
|
||||
return console if manufacturer in PROGRAM_TOPS else heading_name(manufacturer, console)
|
||||
|
||||
|
||||
def generate_systems_index(manufacturers: dict) -> str:
|
||||
@@ -42,8 +42,8 @@ def generate_systems_index(manufacturers: dict) -> str:
|
||||
"Every BIOS file the collection holds, by console. Open a console to "
|
||||
"see each file, the emulators that read it and the setups that list it.",
|
||||
"",
|
||||
f"{_count(total_consoles, 'console')}, {_count(total_files, 'file')} in the "
|
||||
f"repository, from {_count(total_mfr, 'manufacturer')}.",
|
||||
f"{count_text(total_consoles, 'console')}, {count_text(total_files, 'file')} in the "
|
||||
f"repository, from {count_text(total_mfr, 'manufacturer')}.",
|
||||
"",
|
||||
]
|
||||
|
||||
@@ -68,8 +68,8 @@ def generate_systems_index(manufacturers: dict) -> str:
|
||||
"as the data of a game, rather than the BIOS of a machine."),
|
||||
):
|
||||
rows = sorted(
|
||||
((_folder_emulator(console)[0] if group == "programs"
|
||||
else _section_label(mfr, console) if mfr == "Arcade"
|
||||
((folder_emulator(console)[0] if group == "programs"
|
||||
else section_label(mfr, console) if mfr == "Arcade"
|
||||
or (mfr, console) in SECTION_LABELS
|
||||
else _console_display(mfr, console), mfr, console, len(files))
|
||||
for mfr, consoles in manufacturers.items() if kind(mfr) == group
|
||||
@@ -87,11 +87,11 @@ def generate_systems_index(manufacturers: dict) -> str:
|
||||
# every maker cell said Other.
|
||||
lines += ["| Emulator | Files |", "|---------|------:|"]
|
||||
for name, mfr, console, count in rows:
|
||||
href = console_href(_slug(mfr), console).removeprefix("systems/")
|
||||
key = _folder_emulator(console)[1]
|
||||
href = console_href(manufacturer_slug(mfr), console).removeprefix("systems/")
|
||||
key = folder_emulator(console)[1]
|
||||
cell = name.replace("|", "-")
|
||||
cell = f"[{cell}](../emulators/{key}.md)" if key else cell
|
||||
lines.append(f"| {cell} | [{_count(count, 'file')}]({href}) |")
|
||||
lines.append(f"| {cell} | [{count_text(count, 'file')}]({href}) |")
|
||||
lines.append("")
|
||||
continue
|
||||
lines += [
|
||||
@@ -102,18 +102,18 @@ def generate_systems_index(manufacturers: dict) -> str:
|
||||
]
|
||||
for name, mfr, console, count in rows:
|
||||
cell = name.replace("|", "-")
|
||||
href = console_href(_slug(mfr), console).removeprefix("systems/")
|
||||
lines.append(f"| [{cell}]({href}) | {count:,} | [{mfr}]({_slug(mfr)}.md) |")
|
||||
href = console_href(manufacturer_slug(mfr), console).removeprefix("systems/")
|
||||
lines.append(f"| [{cell}]({href}) | {count:,} | [{mfr}]({manufacturer_slug(mfr)}.md) |")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _folder_emulator(folder: str) -> tuple[str, str]:
|
||||
def folder_emulator(folder: str) -> tuple[str, str]:
|
||||
"""The display name and profile of the emulator a folder under Other is
|
||||
named after, by its profile key or its name, else the folder and "".
|
||||
"""
|
||||
profiles = _profiles_on_disk()
|
||||
profiles = profiles_on_disk()
|
||||
if folder in profiles and profiles[folder].get("type") != "alias" and profiles[folder].get("role") != "test":
|
||||
return str(profiles[folder].get("emulator") or folder), folder
|
||||
for key in sorted(profiles):
|
||||
|
||||
@@ -10,7 +10,7 @@ from model import siteinputs
|
||||
from model.composition import count_catalog_matched
|
||||
from model.platforms import load_platform_config
|
||||
from model.profiles import unique_emulator_profiles
|
||||
from sitegen.config import RELEASE_URL, REPO_URL, _timestamp
|
||||
from sitegen.config import RELEASE_URL, REPO_URL, data_timestamp
|
||||
|
||||
|
||||
def compute_stats(db: dict, coverages: dict, profiles: dict) -> dict:
|
||||
@@ -20,7 +20,7 @@ def compute_stats(db: dict, coverages: dict, profiles: dict) -> dict:
|
||||
systems.update(p.get("systems", []))
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"generated_at": _timestamp(),
|
||||
"generated_at": data_timestamp(),
|
||||
"files": db.get("total_files", 0),
|
||||
"size_bytes": db.get("total_size", 0),
|
||||
"platforms": len(coverages),
|
||||
|
||||
@@ -24,7 +24,7 @@ from pathlib import Path
|
||||
from romrecipes import ledger as romrecipes_ledger
|
||||
from resolve.layout import runs_standalone
|
||||
from model.profiles import unique_emulator_profiles
|
||||
from packs.crossref import _first_hash
|
||||
from packs.crossref import first_hash
|
||||
from core.hashing import cut_md5_owner, parse_hash_list
|
||||
from resolve.review import LARGE_FILE_ISSUE_URL, Placement, placement
|
||||
from resolve.validation import deliverable, filter_files_by_mode, installed_with_emulator
|
||||
@@ -125,7 +125,7 @@ def gap_entries(profile: dict, name: str, identity: str, unsourceable: bool) ->
|
||||
if unsourceable:
|
||||
return [f for f in named if f.get("unsourceable")] or named
|
||||
if identity:
|
||||
return [f for f in named if _first_hash(f) == identity] or named
|
||||
return [f for f in named if first_hash(f) == identity] or named
|
||||
return named
|
||||
|
||||
|
||||
|
||||
@@ -23,16 +23,16 @@ from sitegen import markup, steps as sitesteps
|
||||
from sitegen.config import RELEASE_URL
|
||||
from sitegen.guidepage import NO_ZIP_FAQ, devices_meta, first_screen_words, get_page_link
|
||||
from sitegen.guides import fence, terminal_tabs, trust_box
|
||||
from sitegen.home import _group_keys, _next_block, _runs_on, setup_picker
|
||||
from sitegen.install import _installer, has_release_pack
|
||||
from sitegen.home import group_keys, next_block, runs_on_text, setup_picker
|
||||
from sitegen.install import installer_module, has_release_pack
|
||||
from sitegen.readme import NO_PACK, download_links
|
||||
from sitegen.render import _fmt_size
|
||||
from sitegen.render import fmt_size
|
||||
|
||||
|
||||
# Build cross-reference indexes
|
||||
|
||||
|
||||
def _build_file_consumers(db: dict, coverages: dict, profiles: dict) -> FileConsumers:
|
||||
def build_file_consumers(db: dict, coverages: dict, profiles: dict) -> FileConsumers:
|
||||
"""Which platforms and emulators read each collected file."""
|
||||
consumers = FileConsumers(db, build_zip_contents_index(db))
|
||||
consumers.add_platforms({name: cov["config"] for name, cov in coverages.items()})
|
||||
@@ -41,19 +41,19 @@ def _build_file_consumers(db: dict, coverages: dict, profiles: dict) -> FileCons
|
||||
return consumers
|
||||
|
||||
|
||||
def _build_emulator_file_index(profiles: dict) -> dict[str, dict]:
|
||||
def build_emulator_file_index(profiles: dict) -> dict[str, dict]:
|
||||
"""Map emulator_name -> {systems, norm}, for the platform pages.
|
||||
|
||||
norm holds the systems as _norm_system_id reads them: a platform files
|
||||
norm holds the systems as norm_system_id reads them: a platform files
|
||||
the Mega Drive as sega-mega-drive and genesis_plus_gx as sega-megadrive,
|
||||
and an exact match left the RetroArch page with no emulator for it.
|
||||
"""
|
||||
from model.systems import _norm_system_id
|
||||
from model.systems import norm_system_id
|
||||
|
||||
return {
|
||||
name: {
|
||||
"systems": set(profile.get("systems", [])),
|
||||
"norm": {_norm_system_id(str(s)) for s in profile.get("systems", [])},
|
||||
"norm": {norm_system_id(str(s)) for s in profile.get("systems", [])},
|
||||
# Archive members are read inside their archive, never by name.
|
||||
"names": {
|
||||
str(entry["name"]).lower()
|
||||
@@ -86,7 +86,7 @@ def _pack_cell(name: str, record: dict, prefix: str = "") -> str:
|
||||
link = download_links(name, record, "ZIP", page=get_page_link(name, prefix),
|
||||
button=lambda text, url: markup.button(text, url))
|
||||
size = pack.get("download_size") if pack else None
|
||||
return f"{link} ({_fmt_size(size)})" if size else link
|
||||
return f"{link} ({fmt_size(size)})" if size else link
|
||||
|
||||
|
||||
def _own_root_folders(registry: dict) -> dict[str, str]:
|
||||
@@ -113,7 +113,7 @@ def _folder_row(key: str, display: dict[str, str], registry: dict, record: dict,
|
||||
folder = (f"Unzip into `{own_root[key]}`" if key in own_root and zipped
|
||||
else _folder_cell(key, guide))
|
||||
return (f"| [{display[key]}](platforms/{key}.md) | "
|
||||
f"{guide.runs_on or _runs_on(registry[key], guide)} | {folder} | "
|
||||
f"{guide.runs_on or runs_on_text(registry[key], guide)} | {folder} | "
|
||||
f"{_pack_cell(key, record)} |")
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ def _folder_tables(registry: dict, record: dict, display: dict[str, str]) -> lis
|
||||
lines: list[str] = []
|
||||
alone: list[str] = []
|
||||
for group, (label, _description) in DEVICE_GROUPS.items():
|
||||
members = _group_keys(registry, group, display)
|
||||
members = group_keys(registry, group, display)
|
||||
if len(members) == 1 and not ALSO_RUNS.get(group):
|
||||
alone += members
|
||||
continue
|
||||
@@ -247,7 +247,7 @@ def generate_which_pack() -> str:
|
||||
"## Only some consoles?",
|
||||
"",
|
||||
"Pick them here, and get the files and the command. Or use the command's "
|
||||
f"**{_installer().TUI_SYSTEMS_ROW}**.",
|
||||
f"**{installer_module().TUI_SYSTEMS_ROW}**.",
|
||||
"",
|
||||
"<FilePicker />",
|
||||
"",
|
||||
@@ -294,7 +294,7 @@ def generate_which_pack() -> str:
|
||||
]),
|
||||
"Details: [All installer options](wiki/installer.md).",
|
||||
"",
|
||||
*_next_block([
|
||||
*next_block([
|
||||
"[First install, step by step](wiki/first-install.md)",
|
||||
"[When a game does not start](wiki/troubleshooting.md)",
|
||||
]),
|
||||
|
||||
@@ -17,14 +17,14 @@ import os
|
||||
# and a page is only removed once nothing produced it.
|
||||
_produced: set[str] = set()
|
||||
|
||||
def _record(path: str | Path) -> None:
|
||||
def record_written(path: str | Path) -> None:
|
||||
_produced.add(os.path.realpath(str(path)))
|
||||
|
||||
# The reader level label the decoration pass puts above a page's title.
|
||||
LEVEL_LABEL_START = '<span class="rb-level '
|
||||
|
||||
|
||||
def _undecorated(markdown: str) -> str:
|
||||
def undecorated(markdown: str) -> str:
|
||||
"""Return a page body without the front matter the decoration pass adds."""
|
||||
if markdown.startswith("---\n") and "generated_by: retrobios-site" in markdown[:300]:
|
||||
end = markdown.find("\n---\n", 4)
|
||||
@@ -46,12 +46,12 @@ def write_if_changed(path: str, content: str) -> bool:
|
||||
normalizing there too would make its own write look like a no-op and
|
||||
every page would lose its front matter.
|
||||
"""
|
||||
_record(path)
|
||||
return _write_artifact(path, content, normalize=_undecorated)
|
||||
record_written(path)
|
||||
return _write_artifact(path, content, normalize=undecorated)
|
||||
|
||||
def write_decorated(path: str | Path, content: str) -> bool:
|
||||
"""Write the wrapped page, comparing front matter and body together."""
|
||||
_record(path)
|
||||
record_written(path)
|
||||
return _write_artifact(str(path), content)
|
||||
|
||||
# A page body is written as .md and the decoration pass, which runs after
|
||||
@@ -69,7 +69,7 @@ def _was_produced(path: Path) -> bool:
|
||||
for suffix in _PAGE_SUFFIXES if suffix != path.suffix)
|
||||
|
||||
|
||||
def _sweep_generated(docs: Path, directories: list[str]) -> int:
|
||||
def sweep_generated(docs: Path, directories: list[str]) -> int:
|
||||
"""Delete files in the generated tree that this run did not produce."""
|
||||
removed = 0
|
||||
for name in directories:
|
||||
@@ -86,7 +86,7 @@ def _sweep_generated(docs: Path, directories: list[str]) -> int:
|
||||
return removed
|
||||
|
||||
|
||||
def _sweep_top_pages(docs: Path) -> int:
|
||||
def sweep_top_pages(docs: Path) -> int:
|
||||
"""Delete the pages at the root of the docs tree this run did not produce.
|
||||
|
||||
The root holds only generated pages, one per stem (`cross-reference-*`,
|
||||
|
||||
Reference in new issue
Block a user