chore: merge the profile_sync quality work

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:44:52 +01:00
commit 98e871124b
4 files changed
+1366 -934

No files matched your search

+1125 -779
View File
File diff suppressed because it is too large. Load diff
+96 -67
View File
@@ -356,6 +356,95 @@ def resolve_project_word(path: str, trees: Iterable[list[str] | None]) -> str |
return None
def _joined_line(lines: list[str], number: int) -> tuple[str, int, int]:
"""(line, boundary, joined_at) of one scalar line, its wrapped run joined.
boundary is where the line's own text ends, joined_at where the next
line's text starts in the joined line, 0 when nothing was joined.
"""
# A literal block keeps its line breaks, so a citation wrapped after
# `file:` or after a range's comma lost the ranges on the next line
# (gearcoleco `libretro.cpp:` then four ranges). The next line is
# read as the run's continuation, and a run reaching into it is wrapped.
line = lines[number].rstrip()
boundary = len(line)
joined_at = 0
following = lines[number + 1].lstrip() if number + 1 < len(lines) else ""
if PROSE_WRAPPED_RANGE_RE.match(following) and line[-1:].isalnum():
# The break can fall before the colon too: jgenesis wraps
# `.../src/config.rs` then `:76-78,95-99` on the next line.
joined_at = len(line)
line += following
following = ""
# A numbered list after a colon (abuse: `setup.cpp:` then `1. -datadir`)
# is not a range.
if not following[:1].isdigit() or PROSE_LIST_ITEM_RE.match(following):
following = ""
if following and line.endswith(":"):
joined_at = len(line)
line += following
elif following and line.endswith(","):
joined_at = len(line) + 1
line += " " + following
return line, boundary, joined_at
def _prose_events(line: str) -> list[tuple[int, int, re.Match]]:
"""Citations, file names and abbreviated locations of a line, in order."""
return sorted(
[(m.start(), 0, m) for m in PROSE_CITE_RE.finditer(line)]
+ [(m.start(), 1, m) for m in _PROSE_FILE_NAMED_RE.finditer(line)]
+ [(m.start(), 2, m) for m in _PROSE_ABBREVIATED_RE.finditer(line)],
key=lambda event: (event[0], event[1]),
)
def _locate_run(
kind: int, match: re.Match, line: str, lines: list[str], number: int,
known: frozenset[str] | set[str], named: tuple[str, str] | None,
) -> tuple[tuple[str, str, int, tuple[int, int]] | None, tuple[str, str] | None]:
"""(path, role, start, span) of the run an event opens, None when it
opens none, and the file named for the locations after it."""
if kind == 1:
if "://" not in line[max(0, match.start() - 3):match.end()]:
named = (match.group("path"), "")
return None, named
if kind == 2:
if named is None:
return None, named
path, role = named
path_start = match.start()
return (path, role, path_start, (path_start, path_start)), named
found, role, path_start, path_span = _prose_path(line, lines, number, match, known)
if found is None:
return None, named
return (found, role, path_start, path_span), (found, role)
def _run_spans(line: str, match: re.Match) -> tuple[list[tuple[int, int]], int]:
"""Range spans of the run a match opens, and where the run ends."""
spans = [(match.start("range"), match.end("range"))]
end = match.end()
while True:
cont = PROSE_CONT_RE.match(line, end)
if cont is None and (listed := PROSE_CONT_LIST_RE.match(line, end)):
spans.extend(
(item.start(), item.end())
for item in _PROSE_LIST_RANGE_RE.finditer(
line, end, listed.end()
)
)
end = listed.end()
break
if cont is None:
cont = PROSE_CONT_SPACED_RE.match(line, end)
if cont is None:
break
spans.append((cont.start("range"), cont.end("range")))
end = cont.end()
return spans, end
def _prose_runs(
text: str, known: frozenset[str] | set[str] = frozenset()
) -> Iterator[tuple[
@@ -380,79 +469,19 @@ def _prose_runs(
# Where the run wrapped from the line before ends in this one: its
# ranges are that run's, not abbreviated locations of their own.
carried = 0
for number, own in enumerate(lines):
# A literal block keeps its line breaks, so a citation wrapped after
# `file:` or after a range's comma lost the ranges on the next line
# (gearcoleco `libretro.cpp:` then four ranges). The next line is
# read as the run's continuation, and a run reaching into it is wrapped.
line = own.rstrip()
boundary = len(line)
joined_at = 0
following = lines[number + 1].lstrip() if number + 1 < len(lines) else ""
if PROSE_WRAPPED_RANGE_RE.match(following) and line[-1:].isalnum():
# The break can fall before the colon too: jgenesis wraps
# `.../src/config.rs` then `:76-78,95-99` on the next line.
joined_at = len(line)
line += following
following = ""
# A numbered list after a colon (abuse: `setup.cpp:` then `1. -datadir`)
# is not a range.
if not following[:1].isdigit() or PROSE_LIST_ITEM_RE.match(following):
following = ""
if following and line.endswith(":"):
joined_at = len(line)
line += following
elif following and line.endswith(","):
joined_at = len(line) + 1
line += " " + following
for number in range(len(lines)):
line, boundary, joined_at = _joined_line(lines, number)
consumed, carried = carried, 0
events = sorted(
[(m.start(), 0, m) for m in PROSE_CITE_RE.finditer(line)]
+ [(m.start(), 1, m) for m in _PROSE_FILE_NAMED_RE.finditer(line)]
+ [(m.start(), 2, m) for m in _PROSE_ABBREVIATED_RE.finditer(line)],
key=lambda event: (event[0], event[1]),
)
for _start, kind, match in events:
for _start, kind, match in _prose_events(line):
if match.start() >= boundary:
break
if match.start() < consumed:
continue
if kind == 1:
if "://" not in line[max(0, match.start() - 3):match.end()]:
named = (match.group("path"), "")
located, named = _locate_run(kind, match, line, lines, number, known, named)
if located is None:
continue
if kind == 2:
if named is None:
continue
path, role = named
path_start = match.start()
path_span = (path_start, path_start)
else:
path, role, path_start, path_span = _prose_path(
line, lines, number, match, known
)
if path is None:
continue
named = (path, role)
spans = [(match.start("range"), match.end("range"))]
end = match.end()
while True:
cont = PROSE_CONT_RE.match(line, end)
if cont is None and (listed := PROSE_CONT_LIST_RE.match(line, end)):
spans.extend(
(item.start(), item.end())
for item in _PROSE_LIST_RANGE_RE.finditer(
line, end, listed.end()
)
)
end = listed.end()
break
if cont is None:
cont = PROSE_CONT_SPACED_RE.match(line, end)
if cont is None:
break
spans.append((cont.start("range"), cont.end("range")))
end = cont.end()
path, role, path_start, path_span = located
spans, end = _run_spans(line, match)
consumed = end
if end > boundary:
indent = len(lines[number + 1]) - len(lines[number + 1].lstrip())
+16 -10
View File
@@ -419,9 +419,9 @@ def fetch_file(
return None if text == ABSENT else text.splitlines()
if offline:
raise NotCachedError(f"{repo.slug}@{sha[:8]}:{path} is not in the offline cache")
text = _http_text(content_url(repo, sha, path))
write_cache(target, ABSENT if text is None else text)
return None if text is None else text.splitlines()
fetched = _http_text(content_url(repo, sha, path))
write_cache(target, ABSENT if fetched is None else fetched)
return None if fetched is None else fetched.splitlines()
# How long an answer about a moving reference stays trusted. A branch tip, a
@@ -696,6 +696,15 @@ def _github_graphql(
return payload
def _dig(value: object, *keys: str) -> object:
"""The value under nested keys of a JSON answer, None where one is missing."""
for key in keys:
if not isinstance(value, dict) or key not in value:
return None
value = value[key]
return value
def newest_tag(repo: Repo, cache_dir: str, offline: bool = False) -> str | None:
"""The tag on the newest commit.
@@ -708,10 +717,7 @@ def newest_tag(repo: Repo, cache_dir: str, offline: bool = False) -> str | None:
_NEWEST_TAG_QUERY, {"owner": repo.owner, "name": repo.name},
cache_dir, offline,
)
try:
nodes = payload["data"]["repository"]["refs"]["nodes"]
except (TypeError, KeyError):
nodes = None
nodes = _dig(payload, "data", "repository", "refs", "nodes")
if isinstance(nodes, list):
return nodes[0].get("name") if nodes else None
tags = list_tags(repo, cache_dir, offline)
@@ -911,7 +917,7 @@ def ancestry(
if ahead is None:
return None
if repo.family == "github":
behind = forward.get("behind_by")
behind = forward.get("behind_by") if isinstance(forward, dict) else None
else:
behind = _commits_ahead(
_api(_compare_url(repo, head, base), cache_dir, offline), repo.family
@@ -1132,8 +1138,8 @@ def list_gitlinks(
if len(payload) < TREE_PAGE_SIZE:
break
return links
url = _tree_url(repo, sha)
payload = _api(url, cache_dir, offline) if url else None
tree_url = _tree_url(repo, sha)
payload = _api(tree_url, cache_dir, offline) if tree_url else None
if not isinstance(payload, dict):
return {}
return {
+129 -78
View File
@@ -29,6 +29,7 @@ build mode, the way it keys core_version.
from __future__ import annotations
import re
from collections.abc import Callable
from dataclasses import dataclass
import upstream
@@ -175,6 +176,123 @@ def _ancestry(
return relation
@dataclass(frozen=True)
class _Request:
"""One basis read for one build mode, and what its readings carry."""
profile: dict
mode: str
basis: dict
kind: str
stated: str | None
cache_dir: str
offline: bool
profiles: dict | None
recompute: bool
def reading(self, value: str | None, where: str, updates: tuple = ()) -> Reading:
status = MATCH if value == self.stated else DRIFT
return Reading(self.mode, self.kind, self.stated, value, where, status, updates)
def unreadable(self, reason: str) -> Reading:
return Reading(self.mode, self.kind, self.stated, None, reason, UNREADABLE)
def repo_and_pin(self) -> tuple[upstream.Repo, str]:
return _repo_and_pin(self.profile, self.basis, self.mode, self.cache_dir, self.offline)
def _read_none(req: _Request) -> Reading:
if req.recompute:
# A release tagged since the basis was written gives the
# code a version: the advance has to name it.
repo, pin = req.repo_and_pin()
described = upstream.describe(repo, pin, req.cache_dir, req.offline)
if described is not None:
tag, distance = described
return Reading(req.mode, req.kind, req.stated, describe_form(tag, distance, pin),
f"{repo.slug}: tag {tag} is now in "
f"{pin[:7]}'s history", DRIFT)
return req.reading(None, "the code states no version")
def _read_unverified(req: _Request) -> Reading:
return Reading(req.mode, req.kind, req.stated, None, f"not verified: {req.basis.get('why')}",
UNCHECKED)
def _read_package(req: _Request) -> Reading:
artifact = str(req.basis.get("artifact") or "")
if req.basis.get("pattern"):
# An artefact named after its version says it in its name:
# advancemame-0.94.0.tar.gz.
found = read_text_version(artifact, str(req.basis["pattern"]), req.basis.get("format"))
if found is None:
return req.unreadable(f"{artifact}: pattern not found")
return req.reading(found[0], f"named by {artifact}")
return Reading(req.mode, req.kind, req.stated, None, f"read from {artifact}", UNCHECKED)
def _read_alias(req: _Request) -> Reading:
other = (req.profiles or {}).get(str(req.basis.get("of") or ""))
if other is None:
return req.unreadable(f"alias of {req.basis.get('of')}: no such profile")
return req.reading(declared(other, req.mode) if isinstance(other.get("core_version"), dict)
else declared(other, ""), f"alias of {req.basis['of']}")
def _read_file(req: _Request, repo: upstream.Repo, pin: str) -> Reading:
path = str(req.basis.get("path") or "")
lines = upstream.fetch_file(repo, pin, path, req.cache_dir, req.offline)
if lines is None:
return req.unreadable(f"{repo.slug}@{pin[:7]}:{path}: absent")
found = read_text_version("\n".join(lines), str(req.basis.get("pattern") or ""),
req.basis.get("format"))
if found is None:
return req.unreadable(f"{repo.slug}@{pin[:7]}:{path}: pattern not found")
value, line = found
return req.reading(value, f"{repo.slug}@{pin[:7]}:{path}:{line}")
def _read_tag(req: _Request, repo: upstream.Repo, pin: str) -> Reading:
basis = req.basis
if req.recompute:
described = upstream.describe(repo, pin, req.cache_dir, req.offline, basis.get("match"))
if described is None:
return req.unreadable(f"{repo.slug}@{pin[:7]}: no tag in its history")
tag, distance = described
else:
tag, distance = str(basis.get("tag") or ""), basis.get("distance")
commit = upstream.tag_commit(repo, tag, req.cache_dir, req.offline)
if commit is None:
return req.unreadable(f"{repo.slug}: no tag {tag}")
relation = (0, 0) if commit == pin else _ancestry(
repo, commit, pin, req.cache_dir, req.offline)
if relation is None:
return req.unreadable(f"{repo.slug}: {tag}...{pin[:7]} not comparable")
if relation[1]:
return req.unreadable(f"{repo.slug}: tag {tag} is not in {pin[:7]}'s history")
if relation[0] != distance:
return Reading(req.mode, req.kind, req.stated, describe_form(tag, relation[0], pin),
f"{repo.slug}: {pin[:7]} is {relation[0]} commits after "
f"{tag}, the basis says {distance}", DRIFT,
(("distance", relation[0]),))
return req.reading(describe_form(tag, distance, pin),
f"{repo.slug}: tag {tag} + {distance}",
(("tag", tag), ("distance", distance)))
_OFF_FORGE: dict[str, Callable[[_Request], Reading]] = {
"none": _read_none,
"unverified": _read_unverified,
"package": _read_package,
"alias": _read_alias,
}
_ON_FORGE: dict[str, Callable[[_Request, upstream.Repo, str], Reading]] = {
"file": _read_file,
"tag": _read_tag,
}
def read(
profile: dict, mode: str, basis: dict, cache_dir: str, offline: bool,
profiles: dict | None = None, recompute: bool = False,
@@ -185,87 +303,20 @@ def read(
has to: a recorded tag only proves its own distance, and a tag released
between the two pins would go unseen.
"""
stated = declared(profile, mode)
kind = str(basis.get("kind") or "")
def reading(value: str | None, where: str, updates: tuple = ()) -> Reading:
status = MATCH if value == stated else DRIFT
return Reading(mode, kind, stated, value, where, status, updates)
def unreadable(reason: str) -> Reading:
return Reading(mode, kind, stated, None, reason, UNREADABLE)
req = _Request(profile, mode, basis, kind, declared(profile, mode),
cache_dir, offline, profiles, recompute)
try:
if kind == "none":
if recompute:
# A release tagged since the basis was written gives the
# code a version: the advance has to name it.
repo, pin = _repo_and_pin(profile, basis, mode, cache_dir, offline)
described = upstream.describe(repo, pin, cache_dir, offline)
if described is not None:
return Reading(mode, kind, stated, describe_form(*described, pin),
f"{repo.slug}: tag {described[0]} is now in "
f"{pin[:7]}'s history", DRIFT)
return reading(None, "the code states no version")
if kind == "unverified":
return Reading(mode, kind, stated, None, f"not verified: {basis.get('why')}",
UNCHECKED)
if kind == "package":
artifact = str(basis.get("artifact") or "")
if basis.get("pattern"):
# An artefact named after its version says it in its name:
# advancemame-0.94.0.tar.gz.
found = read_text_version(artifact, str(basis["pattern"]), basis.get("format"))
if found is None:
return unreadable(f"{artifact}: pattern not found")
return reading(found[0], f"named by {artifact}")
return Reading(mode, kind, stated, None, f"read from {artifact}", UNCHECKED)
if kind == "alias":
other = (profiles or {}).get(str(basis.get("of") or ""))
if other is None:
return unreadable(f"alias of {basis.get('of')}: no such profile")
return reading(declared(other, mode) if isinstance(other.get("core_version"), dict)
else declared(other, ""), f"alias of {basis['of']}")
repo, pin = _repo_and_pin(profile, basis, mode, cache_dir, offline)
if kind == "file":
path = str(basis.get("path") or "")
lines = upstream.fetch_file(repo, pin, path, cache_dir, offline)
if lines is None:
return unreadable(f"{repo.slug}@{pin[:7]}:{path}: absent")
found = read_text_version("\n".join(lines), str(basis.get("pattern") or ""),
basis.get("format"))
if found is None:
return unreadable(f"{repo.slug}@{pin[:7]}:{path}: pattern not found")
value, line = found
return reading(value, f"{repo.slug}@{pin[:7]}:{path}:{line}")
if kind == "tag":
if recompute:
described = upstream.describe(repo, pin, cache_dir, offline, basis.get("match"))
if described is None:
return unreadable(f"{repo.slug}@{pin[:7]}: no tag in its history")
tag, distance = described
else:
tag, distance = str(basis.get("tag") or ""), basis.get("distance")
commit = upstream.tag_commit(repo, tag, cache_dir, offline)
if commit is None:
return unreadable(f"{repo.slug}: no tag {tag}")
relation = (0, 0) if commit == pin else _ancestry(
repo, commit, pin, cache_dir, offline)
if relation is None:
return unreadable(f"{repo.slug}: {tag}...{pin[:7]} not comparable")
if relation[1]:
return unreadable(f"{repo.slug}: tag {tag} is not in {pin[:7]}'s history")
if relation[0] != distance:
return Reading(mode, kind, stated, describe_form(tag, relation[0], pin),
f"{repo.slug}: {pin[:7]} is {relation[0]} commits after "
f"{tag}, the basis says {distance}", DRIFT,
(("distance", relation[0]),))
return reading(describe_form(tag, distance, pin),
f"{repo.slug}: tag {tag} + {distance}",
(("tag", tag), ("distance", distance)))
off_forge = _OFF_FORGE.get(kind)
if off_forge is not None:
return off_forge(req)
repo, pin = req.repo_and_pin()
on_forge = _ON_FORGE.get(kind)
if on_forge is not None:
return on_forge(req, repo, pin)
except (upstream.UpstreamError, VersionUnreadable) as exc:
return unreadable(str(exc))
return unreadable(f"unknown kind {kind!r}")
return req.unreadable(str(exc))
return req.unreadable(f"unknown kind {kind!r}")
def check(