refactor: public names for cross-module reads

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 22:59:51 +01:00
1 parent f371790dc6
commit 3853ca2f1c
254 files changed
+2955 -2969

No files matched your search

+1 -1
View File
@@ -23,7 +23,7 @@ def toc_slug(text: str) -> str:
return re.sub(r"[-\s]+", "-", text)
def _unique(ident: str, used: set[str]) -> str:
def unique_anchor(ident: str, used: set[str]) -> str:
while ident in used or not ident:
match = IDCOUNT.match(ident)
ident = f"{match[1]}_{int(match[2]) + 1}" if match else f"{ident}_1"
+1 -1
View File
@@ -355,7 +355,7 @@ def repository_output_lock(path: str) -> contextlib.AbstractContextManager[None]
return contextlib.nullcontext()
def _build_timestamp(db: dict | None = None) -> str:
def build_timestamp(db: dict | None = None) -> str:
"""Timestamp for generated artifacts.
Reads the database snapshot the artifact was built from, so rebuilding
+3 -3
View File
@@ -375,7 +375,7 @@ def verify_otp(
Returns (valid, reason_string).
"""
from core.sect233r1 import _N, _ec_mul, _Gx, _Gy, ecdsa_verify_sha256
from core.sect233r1 import N, ec_mul, Gx, Gy, ecdsa_verify_sha256
data = bytearray(Path(filepath).read_bytes())
@@ -436,10 +436,10 @@ def verify_otp(
signature_rs = bytes(data[0x44:0x80])
# Fix up private key: privkey % subgroup_order (Nintendo's ECC lib quirk)
priv_key_int = int.from_bytes(priv_key_raw, "big") % _N
priv_key_int = int.from_bytes(priv_key_raw, "big") % N
# Derive public key from private key: Q = privkey * G
pub_point = _ec_mul(priv_key_int, (_Gx, _Gy))
pub_point = ec_mul(priv_key_int, (Gx, Gy))
if pub_point is None:
return False, "ECC cert: derived public key is point at infinity"
pub_key_xy = pub_point[0].to_bytes(30, "big") + pub_point[1].to_bytes(30, "big")
+2 -2
View File
@@ -21,7 +21,7 @@ import zipfile
from pathlib import Path
# Fixed metadata for deterministic ZIPs
_FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp
FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp
_FIXED_CREATE_SYSTEM = 0 # FAT/DOS (most compatible)
_FIXED_EXTERNAL_ATTR = 0o100644 << 16 # -rw-r--r--
_COMPRESS_LEVEL = 9 # deflate level 9 for determinism
@@ -65,7 +65,7 @@ def rebuild_zip_deterministic(
) as dst:
for info in entries:
out_info = zipfile.ZipInfo(
filename=info.filename, date_time=_FIXED_DATE_TIME
filename=info.filename, date_time=FIXED_DATE_TIME
)
out_info.compress_type = zipfile.ZIP_DEFLATED
out_info.create_system = _FIXED_CREATE_SYSTEM
+5 -5
View File
@@ -7,7 +7,7 @@ import subprocess
def _git_lines(*args: str) -> list[str] | None:
def git_lines(*args: str) -> list[str] | None:
"""Output lines of a git command, or None when git refuses it."""
result = subprocess.run(["git", *args], capture_output=True, text=True, check=False)
if result.returncode != 0:
@@ -27,7 +27,7 @@ def _repo_key(url: str) -> str:
return "/".join(re.split(r"[/:]", path)[-2:]).casefold()
def _project_main_line() -> str | None:
def project_main_line() -> str | None:
"""The project's main line, fetched when this clone does not hold it.
A fork's clone has origin alone. Once the commit is pushed to the fork's
@@ -37,15 +37,15 @@ def _project_main_line() -> str | None:
None leaves the upstream/ and origin/ lines in charge when the clone has
no remote at all and only its uncommitted files can be read.
"""
remotes = _git_lines("remote") or []
remotes = git_lines("remote") or []
if not remotes:
return None
project = {_repo_key(url) for url in PROJECT_URLS}
source = PROJECT_URLS[0]
for remote in remotes:
urls = _git_lines("remote", "get-url", "--all", remote) or []
urls = git_lines("remote", "get-url", "--all", remote) or []
if any(_repo_key(url) in project for url in urls):
if _git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"):
if git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"):
return f"{remote}/main"
source = remote
break
+12 -12
View File
@@ -22,12 +22,12 @@ _F = (1 << 233) | (1 << 74) | 1 # irreducible polynomial
_A = 1
_B = 0x0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD
_Gx = 0x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B
_Gy = 0x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052
Gx = 0x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B
Gy = 0x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052
# Subgroup order
_N = 0x01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7
_N_BITLEN = _N.bit_length() # 233
N = 0x01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7
_N_BITLEN = N.bit_length() # 233
# Cofactor
_H = 2
@@ -156,7 +156,7 @@ def _ec_double(p: tuple[int, int] | None) -> tuple[int, int] | None:
return (x3, y3)
def _ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None:
def ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None:
"""Scalar multiplication k*P using double-and-add."""
if k == 0 or p is _INF:
return _INF
@@ -220,7 +220,7 @@ def ecdsa_verify_sha256(
q_point = (qx, qy)
# Check r, s in [1, n-1]
if not (1 <= r < _N and 1 <= s < _N):
if not (1 <= r < N and 1 <= s < N):
return False
h = hashlib.sha256(message).digest()
@@ -230,20 +230,20 @@ def ecdsa_verify_sha256(
e >>= 256 - _N_BITLEN
# w = s^(-1) mod n
w = _modinv(s, _N)
w = _modinv(s, N)
# u1 = e*w mod n, u2 = r*w mod n
u1 = (e * w) % _N
u2 = (r * w) % _N
u1 = (e * w) % N
u2 = (r * w) % N
# R = u1*G + u2*Q
g_point = (_Gx, _Gy)
r_point = _ec_add(_ec_mul(u1, g_point), _ec_mul(u2, q_point))
g_point = (Gx, Gy)
r_point = _ec_add(ec_mul(u1, g_point), ec_mul(u2, q_point))
if r_point is _INF:
return False
# v = R.x (as integer, already in GF(2^m) which is an integer)
v = r_point[0] % _N
v = r_point[0] % N
return v == r
+46 -46
View File
@@ -311,7 +311,7 @@ def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None:
return RATE_LIMIT_WAITS[waited]
def _fetch(url: str, accept_json: bool = False) -> bytes | None:
def fetch_body(url: str, accept_json: bool = False) -> bytes | None:
"""Body of a GET, or None on 404.
A pass over every profile issues thousands of requests, so a dropped
@@ -355,15 +355,15 @@ def _fetch(url: str, accept_json: bool = False) -> bytes | None:
_sleep(RETRY_BACKOFF[attempt - 1])
def _http_text(url: str) -> str | None:
def http_text(url: str) -> str | None:
"""Text body of a GET, or None on 404. Replaced in tests."""
body = _fetch(url)
body = fetch_body(url)
return None if body is None else body.decode("utf-8", errors="replace")
def _http_json(url: str) -> object | None:
def http_json(url: str) -> object | None:
"""Parsed JSON body of a GET, or None on 404. Replaced in tests."""
body = _fetch(url, accept_json=True)
body = fetch_body(url, accept_json=True)
return None if body is None else json.loads(body.decode())
@@ -419,7 +419,7 @@ 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")
fetched = _http_text(content_url(repo, sha, path))
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()
@@ -441,14 +441,14 @@ def _api_target(url: str, cache_dir: str) -> Path:
def _require_cached(url: str, cache_dir: str, offline: bool, what: str) -> None:
"""Offline, refuse a call the cache holds no answer to, absence included.
_api answers None both for a resource the forge does not have and for
cached_api answers None both for a resource the forge does not have and for
one never asked, and only the first is a fact.
"""
if offline and not _api_target(url, cache_dir).is_file():
raise NotCachedError(f"{what} is not in the offline cache")
def _api(
def cached_api(
url: str, cache_dir: str, offline: bool, max_age: float | None = None,
absent_max_age: float | None = None,
) -> object | None:
@@ -472,7 +472,7 @@ def _api(
return None if raw == ABSENT else json.loads(raw)
if offline:
return None
payload = _http_json(url)
payload = http_json(url)
write_cache(target, ABSENT if payload is None else json.dumps(payload))
return payload
@@ -492,12 +492,12 @@ def fetch_page(url: str, cache_dir: str, offline: bool) -> str | None:
return None if raw == ABSENT else raw
if offline:
return None
text = _http_text(url)
text = http_text(url)
write_cache(target, ABSENT if text is None else text)
return text
def _project(repo: Repo) -> str:
def project_path(repo: Repo) -> str:
return urllib.parse.quote(f"{repo.owner}/{repo.name}", safe="")
@@ -508,7 +508,7 @@ def _commits_url(repo: Repo, date: str | None, branch: str | None = None) -> str
base += f"&sha={urllib.parse.quote(branch, safe='')}"
elif repo.family == "gitlab":
base = (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/commits?per_page=1"
)
if branch:
@@ -537,10 +537,10 @@ def current_slug(repo: Repo, cache_dir: str, offline: bool = False) -> str | Non
name in the payload tells the project moved.
"""
if repo.family == "gitlab":
url, key = f"{repo.api_base}/projects/{_project(repo)}", "path_with_namespace"
url, key = f"{repo.api_base}/projects/{project_path(repo)}", "path_with_namespace"
else:
url, key = f"{repo.api_base}/repos/{repo.slug}", "full_name"
payload = _api(url, cache_dir, offline, MOVING_TTL)
payload = cached_api(url, cache_dir, offline, MOVING_TTL)
if not isinstance(payload, dict):
return None
value = payload.get(key)
@@ -566,7 +566,7 @@ def resolve_head(
_require_cached(
url, cache_dir, offline, f"{repo.slug}: tip of {branch or 'the default branch'}"
)
return _first_sha(_api(url, cache_dir, offline, 0 if fresh else MOVING_TTL))
return _first_sha(cached_api(url, cache_dir, offline, 0 if fresh else MOVING_TTL))
def resolve_commit_at(
@@ -581,7 +581,7 @@ def resolve_commit_at(
if repo.family in ("github", "gitlab"):
url = _commits_url(repo, date, branch)
_require_cached(url, cache_dir, offline, f"{repo.slug}: commit at {date}")
return _first_sha(_api(url, cache_dir, offline))
return _first_sha(cached_api(url, cache_dir, offline))
return _gitea_commit_at(repo, date, cache_dir, offline, branch)
@@ -610,7 +610,7 @@ def _gitea_commit_at(
while True:
url = f"{base}&page={page}"
_require_cached(url, cache_dir, offline, f"{repo.slug}: commit at {date}")
payload = _api(url, cache_dir, offline, MOVING_TTL)
payload = cached_api(url, cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list) or not payload:
return None
for entry in payload:
@@ -637,7 +637,7 @@ def _gitea_commit_date(entry: object) -> datetime | None:
def _tags_url(repo: Repo) -> str:
if repo.family == "gitlab":
return (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/tags?per_page=100"
)
return f"{repo.api_base}/repos/{repo.slug}/tags?per_page=100"
@@ -645,7 +645,7 @@ def _tags_url(repo: Repo) -> str:
def list_tags(repo: Repo, cache_dir: str, offline: bool = False) -> list[str]:
"""Tag names, newest first as the forge orders them."""
payload = _api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
payload = cached_api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list):
return []
return [t["name"] for t in payload if isinstance(t, dict) and t.get("name")]
@@ -728,7 +728,7 @@ def resolve_tag_commit(
repo: Repo, tag: str, cache_dir: str, offline: bool = False
) -> str | None:
"""Commit a tag points at."""
payload = _api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
payload = cached_api(_tags_url(repo), cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list):
return None
for entry in payload:
@@ -746,10 +746,10 @@ def _named_tag_commit(
"""A GitLab or Forgejo tag's commit, asked for by name."""
quoted = urllib.parse.quote(tag, safe="")
if repo.family == "gitlab":
url = f"{repo.api_base}/projects/{_project(repo)}/repository/tags/{quoted}"
url = f"{repo.api_base}/projects/{project_path(repo)}/repository/tags/{quoted}"
else:
url = f"{repo.api_base}/repos/{repo.slug}/tags/{quoted}"
payload = _api(url, cache_dir, offline, absent_max_age=MOVING_TTL)
payload = cached_api(url, cache_dir, offline, absent_max_age=MOVING_TTL)
commit = payload.get("commit") if isinstance(payload, dict) else None
if not isinstance(commit, dict):
return None
@@ -772,7 +772,7 @@ def tag_commit(
quoted = urllib.parse.quote(tag)
# A tag pushed after the first lookup must be seen: the 404 expires,
# the commit a tag names does not.
payload = _api(
payload = cached_api(
f"{repo.api_base}/repos/{repo.slug}/git/ref/tags/{quoted}",
cache_dir,
offline,
@@ -785,7 +785,7 @@ def tag_commit(
return None
if obj.get("type") != "tag":
return obj.get("sha")
annotated = _api(
annotated = cached_api(
f"{repo.api_base}/repos/{repo.slug}/git/tags/{obj.get('sha')}",
cache_dir,
offline,
@@ -796,7 +796,7 @@ def tag_commit(
def _releases_url(repo: Repo) -> str:
if repo.family == "gitlab":
return f"{repo.api_base}/projects/{_project(repo)}/releases"
return f"{repo.api_base}/projects/{project_path(repo)}/releases"
return f"{repo.api_base}/repos/{repo.slug}/releases/latest"
@@ -804,7 +804,7 @@ def latest_release(
repo: Repo, cache_dir: str, offline: bool = False
) -> Release | None:
"""Most recent release the forge exposes."""
payload = _api(_releases_url(repo), cache_dir, offline, MOVING_TTL)
payload = cached_api(_releases_url(repo), cache_dir, offline, MOVING_TTL)
if isinstance(payload, list):
payload = payload[0] if payload else None
if not isinstance(payload, dict):
@@ -819,7 +819,7 @@ def latest_release(
def _compare_url(repo: Repo, base: str, head: str) -> str:
if repo.family == "gitlab":
return (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/compare?from={base}&to={head}"
)
return f"{repo.api_base}/repos/{repo.slug}/compare/{base}...{head}"
@@ -859,7 +859,7 @@ def compare(
repo: Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> CompareResult:
"""Tree difference between two revisions."""
payload = _api(_compare_url(repo, base, head), cache_dir, offline)
payload = cached_api(_compare_url(repo, base, head), cache_dir, offline)
if not isinstance(payload, dict):
return CompareResult([], True)
if repo.family == "gitlab":
@@ -894,7 +894,7 @@ def fork_base(
"""
if repo.family != "github" or fork.family != "github":
return None
payload = _api(
payload = cached_api(
f"{repo.api_base}/repos/{repo.slug}/compare/"
f"{sha}...{fork.owner}:{fork.name}:{fork_sha}",
cache_dir, offline,
@@ -912,7 +912,7 @@ def ancestry(
good. GitHub gives both counts in one answer, GitLab and Forgejo list
one direction only and are asked twice.
"""
forward = _api(_compare_url(repo, base, head), cache_dir, offline)
forward = cached_api(_compare_url(repo, base, head), cache_dir, offline)
ahead = _commits_ahead(forward, repo.family)
if ahead is None:
return None
@@ -920,7 +920,7 @@ def ancestry(
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
cached_api(_compare_url(repo, head, base), cache_dir, offline), repo.family
)
return (ahead, behind) if isinstance(behind, int) else None
@@ -951,7 +951,7 @@ def list_directory(
if repo.family != "github":
return None
url = f"{repo.api_base}/repos/{repo.slug}/git/trees/{sha}:{path.strip('/')}"
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, dict) or payload.get("truncated"):
return None
return sorted(
@@ -976,10 +976,10 @@ def _gitlab_tree(
paths: list[str] = []
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{_project(repo)}/repository/tree"
f"{repo.api_base}/projects/{project_path(repo)}/repository/tree"
f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
return paths, True
paths.extend(
@@ -1028,10 +1028,10 @@ def cache_gitlab_directory(
def _gitlab_archive_files(repo: Repo, sha: str, directory: str) -> dict[str, str]:
url = (
f"{repo.api_base}/projects/{_project(repo)}/repository/archive.tar.gz"
f"{repo.api_base}/projects/{project_path(repo)}/repository/archive.tar.gz"
f"?sha={sha}&path={urllib.parse.quote(directory)}"
)
body = _fetch(url)
body = fetch_body(url)
if body is None:
return {}
prefix = directory + "/"
@@ -1084,7 +1084,7 @@ def list_tree(
url = _tree_url(repo, sha)
if url is None:
return [], True
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, dict):
return [], True
entries = list(payload.get("tree") or [])
@@ -1098,7 +1098,7 @@ def list_tree(
for page in range(2, MAX_TREE_PAGES + 1):
if len(entries) >= total:
break
more = _api(f"{url}&page={page}", cache_dir, offline)
more = cached_api(f"{url}&page={page}", cache_dir, offline)
if not isinstance(more, dict) or not more.get("tree"):
break
entries.extend(more["tree"])
@@ -1123,10 +1123,10 @@ def list_gitlinks(
links: dict[str, str] = {}
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{_project(repo)}/repository/tree"
f"{repo.api_base}/projects/{project_path(repo)}/repository/tree"
f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = _api(url, cache_dir, offline)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
break
links.update(
@@ -1139,7 +1139,7 @@ def list_gitlinks(
break
return links
tree_url = _tree_url(repo, sha)
payload = _api(tree_url, cache_dir, offline) if tree_url else None
payload = cached_api(tree_url, cache_dir, offline) if tree_url else None
if not isinstance(payload, dict):
return {}
return {
@@ -1205,8 +1205,8 @@ def through_gitlink(
def commit_date(repo: Repo, sha: str, cache_dir: str, offline: bool = False) -> str | None:
"""When a revision was committed, as the forge reports it (ISO 8601)."""
if repo.family == "gitlab":
payload = _api(
f"{repo.api_base}/projects/{_project(repo)}/repository/commits/{sha}",
payload = cached_api(
f"{repo.api_base}/projects/{project_path(repo)}/repository/commits/{sha}",
cache_dir, offline,
)
value = payload.get("committed_date") if isinstance(payload, dict) else None
@@ -1215,7 +1215,7 @@ def commit_date(repo: Repo, sha: str, cache_dir: str, offline: bool = False) ->
url = f"{repo.api_base}/repos/{repo.slug}/commits/{sha}"
else:
url = f"{repo.api_base}/repos/{repo.slug}/git/commits/{sha}"
stamp = _gitea_commit_date(_api(url, cache_dir, offline))
stamp = _gitea_commit_date(cached_api(url, cache_dir, offline))
return stamp.isoformat() if stamp is not None else None
@@ -1238,7 +1238,7 @@ def commits_touching(
stamp = urllib.parse.quote(since)
if repo.family == "gitlab":
url = (
f"{repo.api_base}/projects/{_project(repo)}"
f"{repo.api_base}/projects/{project_path(repo)}"
f"/repository/commits?path={quoted}&since={stamp}&per_page=100"
)
elif repo.family == "github":
@@ -1253,7 +1253,7 @@ def commits_touching(
)
# The list grows with every push touching the path: cached for good, the
# triage drift score stayed at whatever the first run counted.
payload = _api(url, cache_dir, offline, MOVING_TTL)
payload = cached_api(url, cache_dir, offline, MOVING_TTL)
if not isinstance(payload, list):
return 0
return sum(