fix: site reads citations through the shared walk

sitegen.sources had its own walk of a profile: it skipped string list
items and read a repository prefix as part of the path, so prboom-plus
and future-pinball-fploader citations that profile_sync tracks were
neither recorded in source-paths.json nor linked. The walk moves to
model.citations, which collect_citations, cited_paths and
link_prose_citations all read.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 00:20:03 +01:00
1 parent 77513c2045
commit 387ca39a9d
9 files changed
+205 -123

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ on:
- "scripts/installer_build/port.py"
- "scripts/model/__init__.py"
- "scripts/model/alternatives.py"
- "scripts/model/citations.py"
- "scripts/model/cliargs.py"
- "scripts/model/collection.py"
- "scripts/model/composition.py"
+144
View File
@@ -0,0 +1,144 @@
"""Every source_ref and prose citation a profile document carries, read the one way every reader shares."""
from __future__ import annotations
from collections import Counter
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any
from core import upstream
from model.profilerepos import declared_repositories
from model.sourceref import RefPart, prose_runs, ref_prose_text, source_ref_values
@dataclass(frozen=True)
class DocumentCitation:
"""One citation of a document and where it is written.
kind is "ref" for a source_ref value, whose ref is one labelled string
of it, and "prose" for a file:line run inside a string scalar or inside
the annotations of a source_ref, which carries its spans and parts.
"""
kind: str
field: str
holder: object
key: object
ref: str
label: str = ""
line: int = 0
path_span: tuple[int, int] = (0, 0)
spans: tuple[tuple[int, int], ...] = ()
parts: tuple[RefPart, ...] = ()
joined_at: int = 0
def known_repositories(document: dict) -> frozenset[str]:
"""The lowercased names of the repositories the document declares.
A name written before a path in prose (`BAM_FPloader FPLoader.cpp:259`)
is the repository the path reads in, not part of the path.
"""
return frozenset(
repo.name.lower()
for _, _, url in declared_repositories(document)
if (repo := upstream.parse_repo(url)) is not None
)
def list_segments(items: list) -> list[object]:
"""The field path segment naming each list item.
A name keys its entry. supermodel declares Games.xml twice, once per
build mode, and both notes answered to files[Games.xml].note: the
history read one note's citations against the other's text. A repeated
name takes its build mode, or its index when the mode repeats too.
"""
keys: list[tuple[str | None, str | None]] = []
for item in items:
name = item.get("name") if isinstance(item, dict) else None
mode = item.get("mode") if isinstance(item, dict) else None
keys.append((
None if name is None else str(name),
mode if isinstance(mode, str) else None,
))
names = Counter(name for name, _ in keys if name is not None)
modes = Counter(key for key in keys if key[0] is not None)
segments: list[object] = []
for index, (name, mode) in enumerate(keys):
if name is None:
segments.append(index)
elif names[name] == 1:
segments.append(name)
elif mode and modes[(name, mode)] == 1:
segments.append(f"{name}@{mode}")
else:
segments.append(f"{name}#{index}")
return segments
def walk_document(
node: object, where: str = ""
) -> Iterator[tuple[str, str, dict | list, object, Any]]:
"""Every citation carrier of the document, with its holder and field path.
Yields ("ref", field, holder, key, value) for each source_ref key and
("str", field, holder, key, value) for every other string scalar, list
items included. One walker builds every field path, so the paths that
name a scalar today still name it when another pass looks it up at
another revision.
"""
if isinstance(node, dict):
for key, value in node.items():
spot = f"{where}.{key}" if where else str(key)
if key == "source_ref":
yield "ref", spot, node, key, value
elif isinstance(value, str):
yield "str", spot, node, key, value
else:
yield from walk_document(value, spot)
elif isinstance(node, list):
segments = list_segments(node)
for index, item in enumerate(node):
spot = f"{where}[{segments[index]}]"
if isinstance(item, str):
yield "str", spot, node, index, item
else:
yield from walk_document(item, spot)
def _prose(
field: str, holder: object, key: object, text: str, known: frozenset[str]
) -> Iterator[DocumentCitation]:
for line, path_span, spans, parts, run, joined_at in prose_runs(text, known):
yield DocumentCitation(
kind="prose", field=field, holder=holder, key=key, ref=run,
line=line, path_span=path_span, spans=spans, parts=parts,
joined_at=joined_at,
)
def document_citations(
document: dict, known: frozenset[str] | None = None
) -> Iterator[DocumentCitation]:
"""Every citation the document carries, in document order.
A source_ref key anywhere in the document is a structured citation, and
the annotations of a string source_ref are prose. Every other string
scalar is scanned for prose runs, a prefix naming a declared repository
read as that repository.
"""
if known is None:
known = known_repositories(document)
for kind, field_name, holder, key, value in walk_document(document):
if kind == "ref":
for label, ref in source_ref_values(value):
yield DocumentCitation(
kind="ref", field=field_name, holder=holder, key=key,
ref=ref, label=label,
)
if isinstance(value, str):
yield from _prose(field_name, holder, key, ref_prose_text(value), known)
continue
yield from _prose(field_name, holder, key, value, known)
+14 -98
View File
@@ -6,17 +6,14 @@ import bisect
import os
import posixpath
import re
from collections import Counter
from collections.abc import Iterable, Iterator
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any
import yaml
from core import upstream
from core.hashing import parse_hash_list
from model.sourceref import RefPart, prose_runs, ref_prose_text, ref_role, source_ref_values
from model.profilerepos import declared_repositories
from model.citations import document_citations, known_repositories
from model.sourceref import RefPart, prose_runs, ref_role
HASH_FIELDS = ("sha1", "md5", "crc32", "sha256", "known_hash_adler32")
@@ -203,66 +200,6 @@ class Citation:
in_comment: bool = False
def _list_segments(items: list) -> list[object]:
"""The field path segment naming each list item.
A name keys its entry. supermodel declares Games.xml twice, once per
build mode, and both notes answered to files[Games.xml].note: the
history read one note's citations against the other's text. A repeated
name takes its build mode, or its index when the mode repeats too.
"""
keys: list[tuple[str | None, str | None]] = []
for item in items:
name = item.get("name") if isinstance(item, dict) else None
mode = item.get("mode") if isinstance(item, dict) else None
keys.append((
None if name is None else str(name),
mode if isinstance(mode, str) else None,
))
names = Counter(name for name, _ in keys if name is not None)
modes = Counter(key for key in keys if key[0] is not None)
segments: list[object] = []
for index, (name, mode) in enumerate(keys):
if name is None:
segments.append(index)
elif names[name] == 1:
segments.append(name)
elif mode and modes[(name, mode)] == 1:
segments.append(f"{name}@{mode}")
else:
segments.append(f"{name}#{index}")
return segments
def _walk_document(
node: object, where: str = ""
) -> Iterator[tuple[str, str, dict | list, object, Any]]:
"""Every citation carrier of the document, with its holder and field path.
Yields ("ref", field, holder, key, value) for each source_ref key and
("str", field, holder, key, value) for every other string scalar. One
walker builds every field path, so the paths that name a scalar today
still name it when another pass looks it up at another revision.
"""
if isinstance(node, dict):
for key, value in node.items():
spot = f"{where}.{key}" if where else str(key)
if key == "source_ref":
yield "ref", spot, node, key, value
elif isinstance(value, str):
yield "str", spot, node, key, value
else:
yield from _walk_document(value, spot)
elif isinstance(node, list):
segments = _list_segments(node)
for index, item in enumerate(node):
spot = f"{where}[{segments[index]}]"
if isinstance(item, str):
yield "str", spot, node, index, item
else:
yield from _walk_document(item, spot)
def _scalar_spans(node: yaml.Node, spans: list[tuple[int, int]]) -> None:
if isinstance(node, yaml.ScalarNode):
spans.append((node.start_mark.index, node.end_mark.index))
@@ -331,38 +268,17 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation]
of the text, not of a field name: anything this walk misses is a
location profile_sync cannot keep honest.
"""
known = frozenset(
repo.name.lower()
for _, _, url in declared_repositories(document)
if (repo := upstream.parse_repo(url)) is not None
)
citations: list[Citation] = []
for kind, field_name, holder, key, value in _walk_document(document):
if kind == "ref":
for label, ref in source_ref_values(value):
citations.append(Citation(
field=field_name, kind="ref", ref=ref,
entry=holder if isinstance(holder, dict) else None,
holder=holder, key=key, label=label,
))
if isinstance(value, str):
for line, path_span, spans, parts, run, joined_at in prose_runs(
ref_prose_text(value), known
):
citations.append(Citation(
field=field_name, kind="prose", ref=run, holder=holder,
key=key, line=line, path_span=path_span, spans=spans,
parts=parts, wrapped=bool(joined_at), joined_at=joined_at,
))
continue
for line, path_span, spans, parts, run, joined_at in prose_runs(
value, known
):
citations.append(Citation(
field=field_name, kind="prose", ref=run, holder=holder, key=key,
line=line, path_span=path_span, spans=spans, parts=parts,
wrapped=bool(joined_at), joined_at=joined_at,
))
known = known_repositories(document)
citations = [
Citation(
field=found.field, kind=found.kind, ref=found.ref,
entry=found.holder if found.kind == "ref" and isinstance(found.holder, dict) else None,
holder=found.holder, key=found.key, label=found.label, line=found.line,
path_span=found.path_span, spans=found.spans, parts=found.parts,
wrapped=bool(found.joined_at), joined_at=found.joined_at,
)
for found in document_citations(document, known)
]
if text is not None:
citations.extend(comment_citations(text, known))
return citations
+8 -20
View File
@@ -7,7 +7,6 @@ import json
import re
import sys
import urllib.parse
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
@@ -15,6 +14,7 @@ from core.text import series
from core import upstream
from core.artifacts import repository_output_lock, write_if_changed
from core.paths import REPO_ROOT
from model.citations import document_citations, known_repositories
from model.sourceref import (
HEX_ADDRESS_RE,
prose_runs,
@@ -224,17 +224,6 @@ def _cached_tree(
return None
def _walk(value: object) -> Iterator[tuple[str, object]]:
"""Every (key, value) of a profile, nested lists and mappings included."""
if isinstance(value, dict):
for key, item in value.items():
yield str(key), item
yield from _walk(item)
elif isinstance(value, list):
for item in value:
yield from _walk(item)
def cited_paths(profile: dict) -> set[str]:
"""Every path a page of the profile could link: the parts of each
source_ref, the file:line citations of its prose and the file its
@@ -246,13 +235,11 @@ def cited_paths(profile: dict) -> set[str]:
str(b["path"]) for b in bases
if isinstance(b, dict) and b.get("kind") == "file" and b.get("path")
}
for key, value in _walk(profile):
if key == "source_ref" and isinstance(value, (str, dict)):
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):
paths.update(part.path for part in parts)
for found in document_citations(profile):
if found.kind == "ref":
paths.update(ref_role(part.path)[1] for part in split_source_ref(found.ref))
else:
paths.update(part.path for part in found.parts)
return {path for path in paths
if _PATH_RE.fullmatch(path) and not is_binary_citation(path)}
@@ -625,11 +612,12 @@ def link_prose_citations(profile: dict, text: str) -> str:
for _label, refs in source_ref_values(entry.get("source_ref"))
for part in split_source_ref(refs)
}
known = known_repositories(profile)
out = []
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, known):
path = parts[0].path
if wrapped or " " in path or not _PATH_RE.fullmatch(path):
continue
+1
View File
@@ -180,6 +180,7 @@ COMMANDS = {
"profiling/bump.py", "profiling/realign.py", "profiling/run.py", "profiling/worktree.py",
"profiling/quota.py", "profiling/sourcepaths.py", "profiling/realignpass.py",
"profiling/versioncheck.py", "profiling/selection.py", "profiling/flagchecks.py",
"model/citations.py",
),
"generate_truth.py": ("resolve/truth.py",),
"diff_truth.py": ("exporter/truthdiff.py", "exporter/diffreport.py"),
+6 -4
View File
@@ -4401,14 +4401,16 @@ class TestCitationSurfaceGuard(unittest.TestCase):
A consumer keying on the field name reopens the gap this closes:
citations outside its list rot while the pin advances. The walker
matches the key once. Everything else goes through the collector.
Every profiling module is read, the audits beside profile_sync
included: mamerefs takes its driver refs from the collector too.
matches the key once, in the model walk the site shares. Everything
else goes through the collector. Every profiling module is read, the
audits beside profile_sync included: mamerefs takes its driver refs
from the collector too.
"""
cli = Path(profile_sync.__file__)
source = "".join(
path.read_text(encoding="utf-8")
for path in [cli, *sorted((cli.parent / "profiling").glob("*.py"))]
for path in [cli, cli.parent / "model" / "citations.py",
*sorted((cli.parent / "profiling").glob("*.py"))]
)
self.assertNotIn('.get("source_ref")', source)
self.assertEqual(source.count('== "source_ref"'), 1)
+25
View File
@@ -997,6 +997,31 @@ class ProseCitationsLinkToThePin(unittest.TestCase):
# The role word names a repository that does not hold it.
self.assertNotIn("](", upstream_only)
BAM = {"source": "https://github.com/ravarcade/BAM_FPloader", "source_commit": "b" * 40,
"notes": "ref: BAM_FPloader FPLoader.cpp:259-305",
"files": [{"name": "x", "source_ref": "FPLoader.cpp:10",
"details": ["see src/hu_stuff.c:1144"]}]}
def test_the_site_reads_the_citations_profile_sync_tracks(self):
"""prboom-plus cites two paths in list items and fploader writes its
repository before the path: the site's own walk missed all three."""
from profiling.citations import collect_citations
from sitegen.sources import cited_paths
tracked = {part.path for found in collect_citations(self.BAM) for part in found.parts}
tracked |= {"FPLoader.cpp"} # the structured ref, whose parts the site splits
self.assertEqual(cited_paths(self.BAM), tracked)
self.assertEqual(tracked, {"FPLoader.cpp", "src/hu_stuff.c"})
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_a_repository_prefix_is_not_part_of_the_path(self):
from sitegen.sources import link_prose_citations
self.assertEqual(
link_prose_citations(self.BAM, self.BAM["notes"]),
"ref: BAM_FPloader [`FPLoader.cpp:259-305`](https://github.com/ravarcade/BAM_FPloader"
"/blob/" + "b" * 40 + "/FPLoader.cpp#L259-L305)")
class ACitationSaysWhoseCodeItIs(unittest.TestCase):
"""Readers could not tell whether the libretro core or the emulator asked
+5
View File
@@ -3498,7 +3498,9 @@
"prboom2/src/e6y.c",
"prboom2/src/g_game.c",
"prboom2/src/gl_hires.c",
"prboom2/src/gl_map.c",
"prboom2/src/gl_shader.c",
"prboom2/src/hu_stuff.c",
"prboom2/src/m_menu.c",
"prboom2/src/m_misc.c",
"prboom2/src/r_demo.c",
@@ -9670,6 +9672,9 @@
"src/llscreen.cpp",
"src/menus.cpp"
],
"github.com/ravarcade/BAM_FPloader@e13007994011ae57dd9d9f48674c1f774183914b": [
"FPLoader.cpp"
],
"github.com/recalbox/pifba@419faa7c3967560f6fa149f2f78b5aedca5b123a": [
"burn/neogeo/d_neogeo.cpp",
"burn/pgm/d_pgm.cpp",
+1 -1
View File
@@ -1377,7 +1377,7 @@ before a release (wiki/release-process.md). Its lines stay in
| Script | Purpose |
|--------|---------|
| `core/` | Standard library only: hashing, ZIP reading and TorrentZip, atomic writes and output locks, `run_cli` and the input errors it prints on one line, the GitHub token, the repository root, forge access (`upstream.py`) |
| `model/` | Data loading: `database.json`, platform configs and the registry, emulator profiles, hardware targets, system ids, the region vocabulary, dump catalogues, release assets, the `source_ref` grammar (`sourceref.py`) |
| `model/` | Data loading: `database.json`, platform configs and the registry, emulator profiles, hardware targets, system ids, the region vocabulary, dump catalogues, release assets, the `source_ref` grammar (`sourceref.py`) and the citation walk every reader shares (`citations.py`) |
| `resolve/` | From a declaration to a file: content checks, `resolve_local_file` and its stages, archive members, launcher layouts, the cores a platform runs, validation, slots, truth |
| `packs/` | The library behind `verify.py`, `generate_pack.py`, `cross_reference.py`, `slots.py` and `refresh_data_dirs.py`: per-file verdicts, coverage and gaps, core extras, slot arbitration, pack naming and archives, manifests, the pack check, the data directory cache |
| `profiling/` | What `profile_sync.py` runs: citations, anchoring, the report and its forms, version checks, detection, triage, the git state a pass reads (uncommitted profiles, the branch's profiles), the anonymous quota, and the guarded writes (recale, bump, prose realignment, `version_basis`) with the site's record of cited paths rebuilt after them |