refactor: parse platform source urls in one place

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:02:11 +01:00
1 parent eebe6a66c3
commit 198e2b2dc7
5 files changed
+111 -52

No files matched your search

+6 -14
View File
@@ -57,7 +57,6 @@ from exporter.originals import (
SourcesIndexUnreadable,
load_sources,
source_key,
source_revision,
wanted_sources,
)
from installer_build import pins as installer_build_pins
@@ -70,6 +69,7 @@ from model.registry import list_registered_platforms, load_data_dir_registry, lo
from model.profiles import load_emulator_profiles, upstream_profile_index
from core.artifacts import write_text_atomic
from model.safeparse import yaml_load
from model.sourcerevision import scraped_revision
from exporter import discover_exporters
from resolve.reconcile import build_native_model
from scripts.scraper import game_dat_importer
@@ -763,15 +763,12 @@ def _os_source(doc: dict) -> dict:
def platform_revision(setup: str, doc: dict, platforms_dir: Path) -> str:
"""The revision the setup's own platform file was scraped at, when the
setup is a registered platform read from the same repository; '' else."""
path = platforms_dir / f"{setup}.yml"
if setup not in load_platform_registry(str(platforms_dir)) or not path.is_file():
if setup not in load_platform_registry(str(platforms_dir)):
return ""
with path.open(encoding="utf-8") as fh:
source = str((yaml_load(fh) or {}).get("source") or "")
repo = upstream.parse_repo(str(_os_source(doc).get("repo") or ""))
if repo is None or f"/{repo.slug.lower()}/" not in source.lower() + "/":
if repo is None:
return ""
return source_revision(source)
return scraped_revision(platforms_dir / f"{setup}.yml", repo.slug)
def romfolder_pin_drift(setup: str, doc: dict, platforms_dir: Path) -> str | None:
@@ -1564,15 +1561,10 @@ def build_variable(lines: list[str], variable: str) -> str | None:
def pin_build_revision(reference: dict, platforms_dir: Path) -> str:
"""The revision of the platform repository its YAML was last scraped at,
'' when the platform is not registered or reads another repository."""
path = platforms_dir / f"{reference.get('platform', '')}.yml"
repo = upstream.parse_repo(str(reference.get("repo") or ""))
if repo is None or not path.is_file():
if repo is None:
return ""
with path.open(encoding="utf-8") as fh:
source = str((yaml_load(fh) or {}).get("source") or "")
if f"/{repo.slug.lower()}/" not in source.lower() + "/":
return ""
return source_revision(source)
return scraped_revision(platforms_dir / f"{reference.get('platform', '')}.yml", repo.slug)
def check_pin_builds(
+72 -14
View File
@@ -8,28 +8,71 @@ read that revision back, so the URL shapes are recognised in one place.
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from model.sources import source_yaml_file
# Each pattern captures the revision. A trailing file path is optional: a
# tree URL names the whole repository at a commit (RetroDECK, MinUI).
_REVISION_PATTERNS = (
re.compile(r"^https://raw\.githubusercontent\.com/[^/]+/[^/]+/([^/]+)(?:/|$)"),
re.compile(r"^https://github\.com/[^/]+/[^/]+/(?:blob|tree)/([^/]+)(?:/|$)"),
re.compile(r"^https://gitlab\.com/.+?/-/(?:raw|blob|tree|archive)/([^/]+)(?:/|$)"),
re.compile(r"^https://codeload\.github\.com/[^/]+/[^/]+/(?:tar\.gz|zip)/([^/]+)$"),
@dataclass(frozen=True)
class SourceURL:
"""A forge URL split into the repository, the revision and the path."""
host: str
owner: str
repo: str
rev: str
path: str
@property
def slug(self) -> str:
return f"{self.owner}/{self.repo}"
# A trailing file path is optional: a tree URL names the whole repository
# at a commit (RetroDECK, MinUI). A GitLab owner is the whole group path.
_SOURCE_PATTERNS = (
re.compile(r"^https://raw\.githubusercontent\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"(?P<rev>[^/]+)(?:/(?P<path>.*))?$"),
re.compile(r"^https://(?P<host>github\.com)/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"(?:blob|tree)/(?P<rev>[^/]+)(?:/(?P<path>.*))?$"),
re.compile(r"^https://(?P<host>gitlab\.com)/(?P<owner>.+?)/(?P<repo>[^/]+)/-/"
r"(?:raw|blob|tree)/(?P<rev>[^/]+)(?:/(?P<path>.*))?$"),
re.compile(r"^https://(?P<host>gitlab\.com)/(?P<owner>.+?)/(?P<repo>[^/]+)/-/"
r"archive/(?P<rev>[^/]+)(?:/.*)?$"),
re.compile(r"^https://codeload\.github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"(?:tar\.gz|zip)/(?P<rev>[^/]+)$"),
re.compile(r"^https://(?P<host>github\.com)/(?P<owner>[^/]+)/(?P<repo>[^/]+?)/?$"),
)
_COMMIT = re.compile(r"[0-9a-f]{40}")
def source_revision(url: str) -> str:
"""The tag or commit a forge URL is read at, '' when it names none."""
for pattern in _REVISION_PATTERNS:
def parse_source(url: str) -> SourceURL | None:
"""The forge, repository, revision and path a forge URL names, None
when it is no shape a scraper pins. A bare repository has rev ''."""
url = str(url or "").strip()
for pattern in _SOURCE_PATTERNS:
match = pattern.match(url)
if match:
return match.group(1)
return ""
parts = match.groupdict()
return SourceURL(
parts.get("host") or "github.com", parts["owner"], parts["repo"],
parts.get("rev") or "", (parts.get("path") or "").rstrip("/"),
)
return None
def source_revision(url: str) -> str:
"""The tag or commit a forge URL is read at, '' when it names none."""
parsed = parse_source(url)
return parsed.rev if parsed else ""
def _names_repo(url: str, repo: str) -> bool:
"""`url` is a URL of `repo` (owner/name, compared without case as the
forges do)."""
parsed = parse_source(url)
return parsed is not None and parsed.slug.lower() == repo.lower()
def required_revision(url: str, repo: str = "", commit: bool = False) -> str:
@@ -39,7 +82,7 @@ def required_revision(url: str, repo: str = "", commit: bool = False) -> str:
refuses a tag or a branch where only a commit pins the read.
"""
revision = source_revision(url)
if repo and f"/{repo}/" not in url:
if repo and not _names_repo(url, repo):
revision = ""
if commit and not _COMMIT.fullmatch(revision):
revision = ""
@@ -57,7 +100,7 @@ def platform_revision(platform_file: Path, repo: str = "", commit: bool = False)
the platform's BIOS list: moving to a new release is a rescrape of the
platform first.
"""
source = str((source_yaml_file(platform_file) or {}).get("source") or "")
source = _platform_source(platform_file)
try:
return required_revision(source, repo, commit)
except ValueError as exc:
@@ -65,3 +108,18 @@ def platform_revision(platform_file: Path, repo: str = "", commit: bool = False)
f"platforms/{platform_file.name} names no pinned revision in its "
f"source ({source!r}): rescrape the platform first"
) from exc
def _platform_source(platform_file: Path) -> str:
return str((source_yaml_file(platform_file) or {}).get("source") or "")
def scraped_revision(platform_file: Path, repo: str = "") -> str:
"""The revision a platform YAML was scraped at, '' when the file is
absent, its source names none or names another repository than `repo`."""
if not platform_file.is_file():
return ""
source = _platform_source(platform_file)
if repo and not _names_repo(source, repo):
return ""
return source_revision(source)
+5 -23
View File
@@ -22,6 +22,7 @@ from model.sourceref import (
source_ref_values,
split_source_ref,
)
from model.sourcerevision import parse_source
from sitegen.render import by_mode, escape_tags
@@ -647,18 +648,6 @@ def _guarded_spans(line: str) -> list[tuple[int, int]]:
return [m.span() for m in re.finditer(r"`[^`]*`|\[[^\]]*\]\([^)]*\)", line)]
# Where a platform's list was read: the forge, the repository, the revision
# and the path inside it, out of the URL its scraper pinned.
_LIST_URL_RES = (
re.compile(r"^https://raw\.githubusercontent\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"(?P<rev>[^/]+)/(?P<path>.+)$"),
re.compile(r"^https://github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/(?:blob|tree)/"
r"(?P<rev>[^/]+)(?:/(?P<path>.+))?$"),
re.compile(r"^https://codeload\.github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/"
r"tar\.gz/(?P<rev>[^/]+)$"),
re.compile(r"^https://(?P<host>gitlab\.com)/(?P<owner>[^/]+)/(?P<repo>[^/]+)/-/"
r"(?:raw|blob)/(?P<rev>[^/]+)/(?P<path>.+)$"),
)
_BRANCHES = frozenset({"master", "main", "db"})
@@ -706,17 +695,10 @@ class ListSource:
def list_source(url: str) -> ListSource | None:
"""The forge, repository, revision and path of a platform's `source:`."""
url = str(url or "").strip()
for pattern in _LIST_URL_RES:
found = pattern.match(url)
if found:
parts = found.groupdict()
return ListSource(parts.get("host") or "github.com", parts["owner"],
parts["repo"], parts["rev"], parts.get("path") or "")
bare = re.match(r"^https://github\.com/([^/]+)/([^/]+?)/?$", url)
if bare:
return ListSource("github.com", bare[1], bare[2], "", "")
return None
parsed = parse_source(url)
if parsed is None:
return None
return ListSource(parsed.host, parsed.owner, parsed.repo, parsed.rev, parsed.path)
def launcher_ref_markdown(source: ListSource | None, ref: str) -> str:
+26 -1
View File
@@ -15,7 +15,13 @@ from unittest import mock
import yaml
from model.sourcerevision import platform_revision, required_revision, source_revision
from model.sourcerevision import (
parse_source,
platform_revision,
required_revision,
scraped_revision,
source_revision,
)
from scraper import base_scraper
from scraper.base_scraper import (
FetchError,
@@ -117,6 +123,25 @@ class SourceRevisionReadsEveryShape(unittest.TestCase):
with self.assertRaises(ValueError):
bad()
def test_a_gitlab_group_is_the_owner(self):
parsed = parse_source("https://gitlab.com/g/sub/proj/-/raw/v1/a/b.xml")
self.assertEqual((parsed.host, parsed.slug, parsed.rev, parsed.path),
("gitlab.com", "g/sub/proj", "v1", "a/b.xml"))
archive = parse_source("https://gitlab.com/o/r/-/archive/10.1/r-10.1.tar.gz")
self.assertEqual((archive.slug, archive.rev, archive.path), ("o/r", "10.1", ""))
def test_a_repository_is_compared_without_case(self):
"""Forge owner and repository names ignore case: check_freshness read
them so, the scrapers' required_revision did not."""
url = "https://raw.githubusercontent.com/ROCKNIX/distribution/20250101/f"
self.assertEqual(required_revision(url, "rocknix/distribution"), "20250101")
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
path = Path(tmp, "p.yml")
path.write_text(f"source: {url}\n")
self.assertEqual(scraped_revision(path, "rocknix/Distribution"), "20250101")
self.assertEqual(scraped_revision(path, "rocknix/other"), "")
self.assertEqual(scraped_revision(Path(tmp, "absent.yml")), "")
def test_a_platform_without_a_revision_raises(self):
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
path = Path(tmp, "p.yml")
+2
View File
@@ -223,6 +223,8 @@ class EvidenceLinksItsSource(unittest.TestCase):
"https://github.com/o/r/tree/v1")
gitlab = list_source("https://gitlab.com/o/r/-/raw/v1/es_bios.xml")
self.assertEqual(gitlab.browse(start=3, end=5), "https://gitlab.com/o/r/-/blob/v1/es_bios.xml#L3-5")
tree = list_source("https://gitlab.com/recalbox/recalbox/-/tree/10.1.1/configs")
self.assertEqual(tree.browse(), "https://gitlab.com/recalbox/recalbox/-/blob/10.1.1/configs")
class EachEntryNamesItsFile(unittest.TestCase):