refactor: split core.upstream by subject

HTTP to the forges moves to core.forgehttp, comparisons, trees and
clone history to core.upstreamtree. core.upstream keeps repositories,
the cache and revisions.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 06:20:52 +01:00
1 parent ce92eff0aa
commit 263a64c0e0
65 files changed
+1417 -1337

No files matched your search

+2
View File
@@ -18,6 +18,7 @@ on:
- "scripts/core/artifacts.py"
- "scripts/core/cli.py"
- "scripts/core/cryptoverify.py"
- "scripts/core/forgehttp.py"
- "scripts/core/gitclone.py"
- "scripts/core/github.py"
- "scripts/core/hashing.py"
@@ -30,6 +31,7 @@ on:
- "scripts/core/sizes.py"
- "scripts/core/text.py"
- "scripts/core/upstream.py"
- "scripts/core/upstreamtree.py"
- "scripts/core/ziptools.py"
- "scripts/devtools/__init__.py"
- "scripts/devtools/prchecks.py"
+3 -3
View File
@@ -12,7 +12,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from acquire.placement import ACQUIRE_DIR, Placement, keep_acquired, place_file
from core import upstream
from core import forgehttp
from core.hashing import parse_hash_list
from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT
from resolve.lookup import held_record_for
@@ -193,10 +193,10 @@ def _get(url: str, unanswered: list[str], timeout: float = 30) -> bytes | None:
report every file as needing a community contribution.
"""
try:
return upstream.fetch_body(
return forgehttp.fetch_body(
url, timeout=timeout, max_bytes=MAX_DOWNLOAD, user_agent="retrobios-fetch/1.0"
)
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
unanswered.append(f"{url}: {exc}")
except ValueError:
pass
+2 -1
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import hashlib
from core import upstream
from core import forgehttp
# Commits listed per page and the most pages walked: a data file older than
@@ -34,7 +35,7 @@ def find_revision(
"""The newest revision whose copy of the path has this md5, and its bytes."""
wanted = md5.lower()
for sha in path_history(repo, path, cache_dir):
data = upstream.fetch_body(upstream.content_url(repo, sha, path))
data = forgehttp.fetch_body(upstream.content_url(repo, sha, path))
if data is not None and hashlib.md5(data).hexdigest() == wanted:
return sha, data
return None
+363
View File
@@ -0,0 +1,363 @@
"""HTTP to the forges: request headers, retries, quota waits, capped reads and the errors they raise."""
from __future__ import annotations
import http.client
import json
import os
import socket
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Callable, Mapping, Protocol, TypeVar
from core.artifacts import atomic_scratch
from core.offline import OFFLINE_ENV, run_is_offline
USER_AGENT = "retrobios-profile-sync/1.0"
# A body read whole into memory is capped at this many bytes.
MAX_RESPONSE_SIZE = 50 * 1024 * 1024
RETRIES = 3
RETRY_BACKOFF = (0.5, 2.0)
# A 429 is waited out, as base_scraper does: git.libretro.com answers it
# a few hundred requests into a pass and serves again a minute later.
RATE_LIMIT_WAITS = (5.0, 20.0, 60.0)
RATE_LIMIT_WAIT_CAP = 120.0
# The hosts the GitHub token is sent to. github.com is not one: a release
# download there redirects to asset storage, and urllib carries the header
# across the redirect.
TOKEN_HOSTS = frozenset({"api.github.com", "raw.githubusercontent.com"})
_T = TypeVar("_T")
_sleep = time.sleep
# Hosts still refusing after every wait. Asking them again in the same pass
# only spends the waits again, while the other forges keep answering.
_exhausted_hosts: set[str] = set()
class UpstreamError(Exception):
"""Any failure while talking to a forge."""
class RateLimitError(UpstreamError):
"""The forge refused the request for quota reasons."""
def __init__(self, message: str, host: str = "") -> None:
super().__init__(message)
self.host = host
class NotCachedError(UpstreamError):
"""An offline read of something the cache never stored.
Distinct from absence: returning None made profile_sync report a file
that exists as GONE, "absent at HEAD, no rename found".
"""
class OfflineError(NotCachedError):
"""A request a run that fetches nothing (RETROBIOS_OFFLINE) would have sent."""
class TruncatedListingError(UpstreamError):
"""A listing the forge served in part: a page that could not be read,
the page cap, or a tree GitHub cut short. What it holds is real, but an
absence from it proves nothing."""
class GoneError(UpstreamError):
"""The upstream is not coming back.
A legal takedown, a resource the forge reports as gone, or a host that
no longer resolves. Retrying costs time and ends in the same place, and
a caller sweeping every profile wants this told apart from a forge
having a bad minute: one is a fact about the project, the other is
weather.
"""
def forge_headers(
url: str, accept: str | None = None, user_agent: str = USER_AGENT
) -> dict[str, str]:
"""Request headers for a forge URL, the GitHub token on TOKEN_HOSTS only.
The host is compared whole: a lookalike such as github.com.example or
a query string naming api.github.com gets no token.
"""
headers = {"User-Agent": user_agent}
if accept is not None:
headers["Accept"] = accept
if urllib.parse.urlsplit(url).hostname in TOKEN_HOSTS:
from core.github import github_token
# GITHUB_TOKEN, else the one gh is logged in with.
token = github_token()
if token:
headers["Authorization"] = f"Bearer {token}"
return headers
def _http_failure(url: str, exc: urllib.error.HTTPError) -> UpstreamError:
"""Classify an HTTP error. Only a real quota signal is fatal.
A forge answering 403 is usually refusing the request, not reporting a
quota: small Forgejo instances behind anti-bot filters do it routinely.
GitHub reports exhaustion with X-RateLimit-Remaining: 0, and 429 is the
standard quota status everywhere, so those two are the only fatal cases.
"""
host = urllib.parse.urlsplit(url).hostname or ""
if exc.code == 429:
retry_after = (exc.headers.get("Retry-After") or "").strip() if exc.headers else ""
wait = f", retry after {retry_after} s" if retry_after.isdigit() else ""
return RateLimitError(f"{url}: HTTP 429{wait}", host)
if exc.code in (410, 451):
reason = "withdrawn for legal reasons" if exc.code == 451 else "gone"
return GoneError(f"{url}: HTTP {exc.code}, {reason}")
if exc.code == 403 and exc.headers is not None:
remaining = exc.headers.get("X-RateLimit-Remaining")
if remaining is not None and remaining.strip() == "0":
return RateLimitError(f"{url}: HTTP 403, quota exhausted", host)
return UpstreamError(f"{url}: HTTP {exc.code}")
def _host_is_unresolvable(exc: BaseException) -> bool:
"""Whether a connection failure is the name itself, not the network.
URLError carries the cause in `reason`, and a wrapped one carries it in
`__cause__`. The walk is bounded because either chain can be cyclic.
"""
seen: BaseException | None = exc
for _ in range(8):
if seen is None:
break
if isinstance(seen, socket.gaierror):
# A resolver that answers nothing at all is the local network:
# every profile would read as gone, and the sweep would report
# nothing to review while it reviewed nothing.
return seen.errno == socket.EAI_NONAME and _resolver_answers()
nested = getattr(seen, "reason", None)
seen = nested if isinstance(nested, BaseException) else seen.__cause__
return False
# A name every forge call depends on: if it does not resolve, the fault is
# local and no host can be declared gone.
RESOLVER_PROBE = "github.com"
def _resolver_answers() -> bool:
"""Whether name resolution works here at all. Replaced in tests."""
try:
socket.getaddrinfo(RESOLVER_PROBE, 443)
except OSError:
return False
return True
class _Headers(Protocol):
def get(self, name: str, /) -> str | None: ...
def requested_wait(headers: _Headers | None) -> float | None:
"""Seconds a 429 asks the client to wait, None when it names none.
Retry-After is the standard header. GoatCounter sends X-Rate-Limit-Reset
instead, the whole seconds left in its window, so one more second is
added: asked again on the second it names, the window is still closed.
"""
if not headers:
return None
retry_after = (headers.get("Retry-After") or "").strip()
if retry_after.isdigit():
return float(retry_after)
reset = (headers.get("X-Rate-Limit-Reset") or "").strip()
return float(reset) + 1 if reset.isdigit() else None
def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None:
"""Seconds to wait before asking again, or None when waiting is futile.
GitHub's exhausted quota (403) resets on the hour. A 429 names its wait
(requested_wait), which is followed up to a cap, else the fixed steps.
"""
if exc.code != 429 or waited >= len(RATE_LIMIT_WAITS):
return None
delay = requested_wait(exc.headers)
if delay is not None:
return delay if delay <= RATE_LIMIT_WAIT_CAP else None
return RATE_LIMIT_WAITS[waited]
class _Readable(Protocol):
def read(self, size: int = ..., /) -> bytes: ...
def read_limited(resp: _Readable, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes:
"""Read a response whole, ValueError past `max_bytes`."""
chunks: list[bytes] = []
total = 0
while True:
chunk = resp.read(65536)
if not chunk:
break
total += len(chunk)
if total > max_bytes:
raise ValueError(f"Response exceeds {max_bytes} byte limit")
chunks.append(chunk)
return b"".join(chunks)
def open_retrying(
request: urllib.request.Request,
consume: Callable[[http.client.HTTPResponse], _T],
timeout: float = 30,
) -> _T:
"""Open `request` and hand the response to `consume`.
A pass over every profile issues thousands of requests, so a dropped
connection or a transient 5xx is a certainty rather than an accident.
Those are retried, a definitive answer from the forge is not. A rate
limit is waited out, and a host that outlasts the waits is not asked
again in this process. What ends the attempts is raised as urllib gave
it, except a host that does not resolve (GoneError) and a host muted
earlier (RateLimitError). A run that fetches nothing (run_is_offline)
raises OfflineError before anything goes out. A file: address is read
from this machine and is never refused.
"""
url = request.full_url
if run_is_offline() and request.type != "file":
raise OfflineError(f"{url}: {OFFLINE_ENV} is set, nothing is fetched")
host = urllib.parse.urlsplit(url).hostname or ""
if host in _exhausted_hosts:
raise RateLimitError(f"{url}: {host} rate limited earlier in this run", host)
attempt = 0
waited = 0
while True:
try:
with urllib.request.urlopen(request, timeout=timeout) as resp:
return consume(resp)
except urllib.error.HTTPError as exc:
if isinstance(_http_failure(url, exc), RateLimitError):
delay = _rate_limit_wait(exc, waited)
if delay is None:
_exhausted_hosts.add(host)
raise
waited += 1
_sleep(delay)
continue
if exc.code < 500:
raise
failure: BaseException = exc
except (urllib.error.URLError, http.client.HTTPException, OSError) as exc:
if _host_is_unresolvable(exc):
raise GoneError(f"{url}: host does not resolve") from exc
failure = exc
attempt += 1
if attempt >= RETRIES:
raise failure
_sleep(RETRY_BACKOFF[attempt - 1])
def fetch_body(
url: str,
accept_json: bool = False,
*,
timeout: float = 30,
max_bytes: int = MAX_RESPONSE_SIZE,
user_agent: str = USER_AGENT,
) -> bytes | None:
"""Body of a GET, or None on 404, retried as open_retrying does.
A failure raises UpstreamError (RateLimitError, GoneError), a body over
`max_bytes` ValueError.
"""
accept = "application/json" if accept_json else None
req = urllib.request.Request(url, headers=forge_headers(url, accept, user_agent))
try:
return open_retrying(req, lambda resp: read_limited(resp, max_bytes), timeout)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
raise _http_failure(url, exc) from exc
except (urllib.error.URLError, http.client.HTTPException, OSError) as exc:
raise UpstreamError(f"{url}: {exc}") from exc
def http_text(url: str) -> str | None:
"""Text body of a GET, or None on 404. Replaced in tests."""
body = fetch_body(url)
return None if body is None else body.decode("utf-8", errors="replace")
def remote_etag(url: str, timeout: float = 30) -> str | None:
"""ETag, else Last-Modified, of a HEAD; "" when neither is sent, None
when the server does not answer."""
req = urllib.request.Request(
url, method="HEAD", headers=forge_headers(url, user_agent="retrobios/1.0")
)
try:
return open_retrying(
req,
lambda resp: resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "",
timeout,
)
except (urllib.error.URLError, http.client.HTTPException, OSError, UpstreamError):
return None
class _Refused(Exception):
"""A finished download the caller's check turned down."""
def download(
url: str,
destination: str | os.PathLike[str],
*,
headers: Mapping[str, str] | None = None,
timeout: float = 300,
max_bytes: int | None = None,
user_agent: str = USER_AGENT,
accept: Callable[[str], bool] | None = None,
) -> http.client.HTTPMessage | None:
"""Stream `url` into `destination`, whole or not at all, and return the
response headers.
The body goes to a unique scratch beside the destination, renamed into
place once complete, so a reader or an interrupted run never sees half a
file and two runs never interleave their bytes. Each attempt of
open_retrying starts the scratch over: a stream cut midway is retried
like a refused connection. `headers` add to or replace forge_headers().
A body past `max_bytes` raises ValueError. `accept` judges the finished
scratch by its path: refused, nothing is written and None is returned.
A failure raises as open_retrying raises it.
"""
request = urllib.request.Request(
url, headers={**forge_headers(url, user_agent=user_agent), **(headers or {})}
)
def save(scratch: str, resp: http.client.HTTPResponse) -> http.client.HTTPMessage:
total = 0
with open(scratch, "wb") as out:
while chunk := resp.read(1 << 20):
total += len(chunk)
if max_bytes is not None and total > max_bytes:
raise ValueError(f"{url}: response exceeds {max_bytes} byte limit")
out.write(chunk)
return resp.headers
try:
with atomic_scratch(destination) as scratch:
served = open_retrying(request, lambda resp: save(scratch, resp), timeout)
if accept is not None and not accept(scratch):
raise _Refused
except _Refused:
return None
return served
def http_json(url: str) -> object | None:
"""Parsed JSON body of a GET, or None on 404. Replaced in tests."""
body = fetch_body(url, accept_json=True)
return None if body is None else json.loads(body.decode())
+16 -871
View File
@@ -1,22 +1,15 @@
"""Access to upstream source repositories.
Resolves revisions, fetches files by sha, and compares trees across the
forge families the emulator profiles point at. Knows nothing about profile
structure.
Resolves revisions and fetches files by sha across the forge families the
emulator profiles point at. Knows nothing about profile structure.
"""
from __future__ import annotations
import hashlib
import http.client
import io
import json
import os
import shutil
import socket
import subprocess
import tarfile
import tempfile
import time
import urllib.error
import urllib.parse
@@ -24,28 +17,14 @@ import urllib.request
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Callable, Mapping, Protocol, TypeVar
from core.artifacts import atomic_scratch, write_text_atomic
from core.offline import OFFLINE_ENV, run_is_offline
from core.artifacts import write_text_atomic
from core import forgehttp
from core.offline import run_is_offline
USER_AGENT = "retrobios-profile-sync/1.0"
# Where fetched upstream files live, shared by every reader of this cache.
CACHE_DIR = ".cache/upstream"
ABSENT = "\0absent\0"
GITHUB_COMPARE_CAP = 300
# A body read whole into memory is capped at this many bytes.
MAX_RESPONSE_SIZE = 50 * 1024 * 1024
RETRIES = 3
RETRY_BACKOFF = (0.5, 2.0)
# A 429 is waited out, as base_scraper does: git.libretro.com answers it
# a few hundred requests into a pass and serves again a minute later.
RATE_LIMIT_WAITS = (5.0, 20.0, 60.0)
RATE_LIMIT_WAIT_CAP = 120.0
# The hosts the GitHub token is sent to. github.com is not one: a release
# download there redirects to asset storage, and urllib carries the header
# across the redirect.
TOKEN_HOSTS = frozenset({"api.github.com", "raw.githubusercontent.com"})
_HOSTS: dict[str, tuple[str, str, str]] = {
"github.com": (
@@ -97,54 +76,6 @@ _HOSTS: dict[str, tuple[str, str, str]] = {
}
_T = TypeVar("_T")
_sleep = time.sleep
# Hosts still refusing after every wait. Asking them again in the same pass
# only spends the waits again, while the other forges keep answering.
_exhausted_hosts: set[str] = set()
class UpstreamError(Exception):
"""Any failure while talking to a forge."""
class RateLimitError(UpstreamError):
"""The forge refused the request for quota reasons."""
def __init__(self, message: str, host: str = "") -> None:
super().__init__(message)
self.host = host
class NotCachedError(UpstreamError):
"""An offline read of something the cache never stored.
Distinct from absence: returning None made profile_sync report a file
that exists as GONE, "absent at HEAD, no rename found".
"""
class OfflineError(NotCachedError):
"""A request a run that fetches nothing (RETROBIOS_OFFLINE) would have sent."""
class TruncatedListingError(UpstreamError):
"""A listing the forge served in part: a page that could not be read,
the page cap, or a tree GitHub cut short. What it holds is real, but an
absence from it proves nothing."""
class GoneError(UpstreamError):
"""The upstream is not coming back.
A legal takedown, a resource the forge reports as gone, or a host that
no longer resolves. Retrying costs time and ends in the same place, and
a caller sweeping every profile wants this told apart from a forge
having a bad minute: one is a fact about the project, the other is
weather.
"""
@dataclass(frozen=True)
class Repo:
host: str
@@ -166,23 +97,6 @@ class Release:
is_prerelease: bool
@dataclass(frozen=True)
class FileChange:
status: str
path: str
previous_path: str | None
@dataclass(frozen=True)
class CompareResult:
files: list[FileChange]
truncated: bool
# The forge reports the two revisions on separate lines of history: the
# base is no ancestor of the head. A pin in that state survives only
# while the forge keeps the orphaned object (advancemame, 2026-10-05).
diverged: bool = False
def parse_repo(url: str) -> Repo | None:
"""Build a Repo from a forge URL, or None when the host is unknown."""
if not url:
@@ -240,291 +154,6 @@ def content_url(repo: Repo, sha: str, path: str) -> str:
return f"{repo.api_base}/repos/{repo.owner}/{repo.name}/raw/{quoted}?ref={sha}"
def forge_headers(
url: str, accept: str | None = None, user_agent: str = USER_AGENT
) -> dict[str, str]:
"""Request headers for a forge URL, the GitHub token on TOKEN_HOSTS only.
The host is compared whole: a lookalike such as github.com.example or
a query string naming api.github.com gets no token.
"""
headers = {"User-Agent": user_agent}
if accept is not None:
headers["Accept"] = accept
if urllib.parse.urlsplit(url).hostname in TOKEN_HOSTS:
from core.github import github_token
# GITHUB_TOKEN, else the one gh is logged in with.
token = github_token()
if token:
headers["Authorization"] = f"Bearer {token}"
return headers
def _http_failure(url: str, exc: urllib.error.HTTPError) -> UpstreamError:
"""Classify an HTTP error. Only a real quota signal is fatal.
A forge answering 403 is usually refusing the request, not reporting a
quota: small Forgejo instances behind anti-bot filters do it routinely.
GitHub reports exhaustion with X-RateLimit-Remaining: 0, and 429 is the
standard quota status everywhere, so those two are the only fatal cases.
"""
host = urllib.parse.urlsplit(url).hostname or ""
if exc.code == 429:
retry_after = (exc.headers.get("Retry-After") or "").strip() if exc.headers else ""
wait = f", retry after {retry_after} s" if retry_after.isdigit() else ""
return RateLimitError(f"{url}: HTTP 429{wait}", host)
if exc.code in (410, 451):
reason = "withdrawn for legal reasons" if exc.code == 451 else "gone"
return GoneError(f"{url}: HTTP {exc.code}, {reason}")
if exc.code == 403 and exc.headers is not None:
remaining = exc.headers.get("X-RateLimit-Remaining")
if remaining is not None and remaining.strip() == "0":
return RateLimitError(f"{url}: HTTP 403, quota exhausted", host)
return UpstreamError(f"{url}: HTTP {exc.code}")
def _host_is_unresolvable(exc: BaseException) -> bool:
"""Whether a connection failure is the name itself, not the network.
URLError carries the cause in `reason`, and a wrapped one carries it in
`__cause__`. The walk is bounded because either chain can be cyclic.
"""
seen: BaseException | None = exc
for _ in range(8):
if seen is None:
break
if isinstance(seen, socket.gaierror):
# A resolver that answers nothing at all is the local network:
# every profile would read as gone, and the sweep would report
# nothing to review while it reviewed nothing.
return seen.errno == socket.EAI_NONAME and _resolver_answers()
nested = getattr(seen, "reason", None)
seen = nested if isinstance(nested, BaseException) else seen.__cause__
return False
# A name every forge call depends on: if it does not resolve, the fault is
# local and no host can be declared gone.
RESOLVER_PROBE = "github.com"
def _resolver_answers() -> bool:
"""Whether name resolution works here at all. Replaced in tests."""
try:
socket.getaddrinfo(RESOLVER_PROBE, 443)
except OSError:
return False
return True
class _Headers(Protocol):
def get(self, name: str, /) -> str | None: ...
def requested_wait(headers: _Headers | None) -> float | None:
"""Seconds a 429 asks the client to wait, None when it names none.
Retry-After is the standard header. GoatCounter sends X-Rate-Limit-Reset
instead, the whole seconds left in its window, so one more second is
added: asked again on the second it names, the window is still closed.
"""
if not headers:
return None
retry_after = (headers.get("Retry-After") or "").strip()
if retry_after.isdigit():
return float(retry_after)
reset = (headers.get("X-Rate-Limit-Reset") or "").strip()
return float(reset) + 1 if reset.isdigit() else None
def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None:
"""Seconds to wait before asking again, or None when waiting is futile.
GitHub's exhausted quota (403) resets on the hour. A 429 names its wait
(requested_wait), which is followed up to a cap, else the fixed steps.
"""
if exc.code != 429 or waited >= len(RATE_LIMIT_WAITS):
return None
delay = requested_wait(exc.headers)
if delay is not None:
return delay if delay <= RATE_LIMIT_WAIT_CAP else None
return RATE_LIMIT_WAITS[waited]
class _Readable(Protocol):
def read(self, size: int = ..., /) -> bytes: ...
def read_limited(resp: _Readable, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes:
"""Read a response whole, ValueError past `max_bytes`."""
chunks: list[bytes] = []
total = 0
while True:
chunk = resp.read(65536)
if not chunk:
break
total += len(chunk)
if total > max_bytes:
raise ValueError(f"Response exceeds {max_bytes} byte limit")
chunks.append(chunk)
return b"".join(chunks)
def open_retrying(
request: urllib.request.Request,
consume: Callable[[http.client.HTTPResponse], _T],
timeout: float = 30,
) -> _T:
"""Open `request` and hand the response to `consume`.
A pass over every profile issues thousands of requests, so a dropped
connection or a transient 5xx is a certainty rather than an accident.
Those are retried, a definitive answer from the forge is not. A rate
limit is waited out, and a host that outlasts the waits is not asked
again in this process. What ends the attempts is raised as urllib gave
it, except a host that does not resolve (GoneError) and a host muted
earlier (RateLimitError). A run that fetches nothing (run_is_offline)
raises OfflineError before anything goes out. A file: address is read
from this machine and is never refused.
"""
url = request.full_url
if run_is_offline() and request.type != "file":
raise OfflineError(f"{url}: {OFFLINE_ENV} is set, nothing is fetched")
host = urllib.parse.urlsplit(url).hostname or ""
if host in _exhausted_hosts:
raise RateLimitError(f"{url}: {host} rate limited earlier in this run", host)
attempt = 0
waited = 0
while True:
try:
with urllib.request.urlopen(request, timeout=timeout) as resp:
return consume(resp)
except urllib.error.HTTPError as exc:
if isinstance(_http_failure(url, exc), RateLimitError):
delay = _rate_limit_wait(exc, waited)
if delay is None:
_exhausted_hosts.add(host)
raise
waited += 1
_sleep(delay)
continue
if exc.code < 500:
raise
failure: BaseException = exc
except (urllib.error.URLError, http.client.HTTPException, OSError) as exc:
if _host_is_unresolvable(exc):
raise GoneError(f"{url}: host does not resolve") from exc
failure = exc
attempt += 1
if attempt >= RETRIES:
raise failure
_sleep(RETRY_BACKOFF[attempt - 1])
def fetch_body(
url: str,
accept_json: bool = False,
*,
timeout: float = 30,
max_bytes: int = MAX_RESPONSE_SIZE,
user_agent: str = USER_AGENT,
) -> bytes | None:
"""Body of a GET, or None on 404, retried as open_retrying does.
A failure raises UpstreamError (RateLimitError, GoneError), a body over
`max_bytes` ValueError.
"""
accept = "application/json" if accept_json else None
req = urllib.request.Request(url, headers=forge_headers(url, accept, user_agent))
try:
return open_retrying(req, lambda resp: read_limited(resp, max_bytes), timeout)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
raise _http_failure(url, exc) from exc
except (urllib.error.URLError, http.client.HTTPException, OSError) as exc:
raise UpstreamError(f"{url}: {exc}") from exc
def http_text(url: str) -> str | None:
"""Text body of a GET, or None on 404. Replaced in tests."""
body = fetch_body(url)
return None if body is None else body.decode("utf-8", errors="replace")
def remote_etag(url: str, timeout: float = 30) -> str | None:
"""ETag, else Last-Modified, of a HEAD; "" when neither is sent, None
when the server does not answer."""
req = urllib.request.Request(
url, method="HEAD", headers=forge_headers(url, user_agent="retrobios/1.0")
)
try:
return open_retrying(
req,
lambda resp: resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "",
timeout,
)
except (urllib.error.URLError, http.client.HTTPException, OSError, UpstreamError):
return None
class _Refused(Exception):
"""A finished download the caller's check turned down."""
def download(
url: str,
destination: str | os.PathLike[str],
*,
headers: Mapping[str, str] | None = None,
timeout: float = 300,
max_bytes: int | None = None,
user_agent: str = USER_AGENT,
accept: Callable[[str], bool] | None = None,
) -> http.client.HTTPMessage | None:
"""Stream `url` into `destination`, whole or not at all, and return the
response headers.
The body goes to a unique scratch beside the destination, renamed into
place once complete, so a reader or an interrupted run never sees half a
file and two runs never interleave their bytes. Each attempt of
open_retrying starts the scratch over: a stream cut midway is retried
like a refused connection. `headers` add to or replace forge_headers().
A body past `max_bytes` raises ValueError. `accept` judges the finished
scratch by its path: refused, nothing is written and None is returned.
A failure raises as open_retrying raises it.
"""
request = urllib.request.Request(
url, headers={**forge_headers(url, user_agent=user_agent), **(headers or {})}
)
def save(scratch: str, resp: http.client.HTTPResponse) -> http.client.HTTPMessage:
total = 0
with open(scratch, "wb") as out:
while chunk := resp.read(1 << 20):
total += len(chunk)
if max_bytes is not None and total > max_bytes:
raise ValueError(f"{url}: response exceeds {max_bytes} byte limit")
out.write(chunk)
return resp.headers
try:
with atomic_scratch(destination) as scratch:
served = open_retrying(request, lambda resp: save(scratch, resp), timeout)
if accept is not None and not accept(scratch):
raise _Refused
except _Refused:
return None
return served
def http_json(url: str) -> object | None:
"""Parsed JSON body of a GET, or None on 404. Replaced in tests."""
body = fetch_body(url, accept_json=True)
return None if body is None else json.loads(body.decode())
def cache_path(cache_dir: str, repo: Repo, sha: str, path: str) -> Path:
"""Content-addressed location for one path at one revision."""
root = Path(cache_dir) / repo.host / repo.owner / repo.name / sha
@@ -569,8 +198,8 @@ def fetch_file(
text = target.read_text(encoding="utf-8")
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))
raise forgehttp.NotCachedError(f"{repo.slug}@{sha[:8]}:{path} is not in the offline cache")
fetched = forgehttp.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()
@@ -596,7 +225,7 @@ def _require_cached(url: str, cache_dir: str, offline: bool, what: str) -> None:
one never asked, and only the first is a fact.
"""
if run_is_offline(offline) and not _api_target(url, cache_dir).is_file():
raise NotCachedError(f"{what} is not in the offline cache")
raise forgehttp.NotCachedError(f"{what} is not in the offline cache")
def cached_api(
@@ -624,7 +253,7 @@ def cached_api(
return None if raw == ABSENT else json.loads(raw)
if offline:
return None
payload = http_json(url)
payload = forgehttp.http_json(url)
write_cache(target, ABSENT if payload is None else json.dumps(payload))
return payload
@@ -646,8 +275,8 @@ def fetch_page(url: str, cache_dir: str, offline: bool) -> str | None:
raw = target.read_text(encoding="utf-8")
return None if raw == ABSENT else raw
if offline:
raise NotCachedError(f"{url} is not in the offline cache")
text = http_text(url)
raise forgehttp.NotCachedError(f"{url} is not in the offline cache")
text = forgehttp.http_text(url)
write_cache(target, ABSENT if text is None else text)
return text
@@ -723,8 +352,8 @@ def resolve_head(
url = _commits_url(repo, None, branch)
if cache_dir is None:
if offline:
raise NotCachedError(f"{repo.slug}: no cache to read offline")
return _first_sha(http_json(url))
raise forgehttp.NotCachedError(f"{repo.slug}: no cache to read offline")
return _first_sha(forgehttp.http_json(url))
_require_cached(
url, cache_dir, offline, f"{repo.slug}: tip of {branch or 'the default branch'}"
)
@@ -841,7 +470,7 @@ def _github_graphql(
token = github_token()
if offline or not token:
return None
headers = forge_headers(GITHUB_GRAPHQL, "application/json")
headers = forgehttp.forge_headers(GITHUB_GRAPHQL, "application/json")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
GITHUB_GRAPHQL, data=body.encode(), headers=headers, method="POST"
@@ -850,9 +479,9 @@ def _github_graphql(
with urllib.request.urlopen(req, timeout=30) as resp:
payload = json.loads(resp.read().decode())
except urllib.error.HTTPError as exc:
raise _http_failure(GITHUB_GRAPHQL, exc) from exc
raise forgehttp._http_failure(GITHUB_GRAPHQL, exc) from exc
except (urllib.error.URLError, http.client.HTTPException, OSError) as exc:
raise UpstreamError(f"{GITHUB_GRAPHQL}: {exc}") from exc
raise forgehttp.UpstreamError(f"{GITHUB_GRAPHQL}: {exc}") from exc
if not isinstance(payload, dict) or payload.get("errors"):
return None
write_cache(target, json.dumps(payload))
@@ -979,389 +608,6 @@ def latest_release(
return Release(str(tag), str(stamp)[:10], bool(payload.get("prerelease")))
def _compare_url(repo: Repo, base: str, head: str) -> str:
if repo.family == "gitlab":
return (
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}"
def _changes_from_github(payload: dict) -> list[FileChange]:
return [
FileChange(
entry.get("status", "modified"),
entry.get("filename", ""),
entry.get("previous_filename"),
)
for entry in (payload.get("files") or [])
if isinstance(entry, dict)
]
def _changes_from_gitlab(payload: dict) -> list[FileChange]:
changes = []
for entry in payload.get("diffs") or []:
if not isinstance(entry, dict):
continue
if entry.get("renamed_file"):
status = "renamed"
elif entry.get("new_file"):
status = "added"
elif entry.get("deleted_file"):
status = "removed"
else:
status = "modified"
previous = entry.get("old_path") if status == "renamed" else None
changes.append(FileChange(status, entry.get("new_path", ""), previous))
return changes
def compare(
repo: Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> CompareResult:
"""Tree difference between two revisions."""
payload = cached_api(_compare_url(repo, base, head), cache_dir, offline)
if not isinstance(payload, dict):
return CompareResult([], True)
if repo.family == "gitlab":
files = _changes_from_gitlab(payload)
else:
files = _changes_from_github(payload)
truncated = bool(payload.get("truncated")) or len(files) >= GITHUB_COMPARE_CAP
return CompareResult(files, truncated, payload.get("status") == "diverged")
def _commits_ahead(payload: object, family: str) -> int | None:
"""Commits the compare head carries that its base does not."""
if not isinstance(payload, dict):
return None
if family == "github":
value = payload.get("ahead_by")
elif family == "gitlab":
value = len(payload.get("commits") or [])
else:
value = payload.get("total_commits")
return value if isinstance(value, int) else None
def fork_base(
repo: Repo, sha: str, fork: Repo, fork_sha: str, cache_dir: str,
offline: bool = False,
) -> str | None:
"""The commit of ``repo`` that ``fork`` at ``fork_sha`` has merged up to.
GitHub compares across a fork network and names the merge base. Two
repositories outside one network answer 404, and None is returned.
"""
if repo.family != "github" or fork.family != "github":
return None
payload = cached_api(
f"{repo.api_base}/repos/{repo.slug}/compare/"
f"{sha}...{fork.owner}:{fork.name}:{fork_sha}",
cache_dir, offline,
)
base = payload.get("merge_base_commit") if isinstance(payload, dict) else None
return base.get("sha") if isinstance(base, dict) else None
def ancestry(
repo: Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> tuple[int, int] | None:
"""(ahead, behind): commits head has that base lacks, and the reverse.
Two shas never change their history, so both answers are cached for
good. GitHub gives both counts in one answer, GitLab and Forgejo list
one direction only and are asked twice.
"""
forward = cached_api(_compare_url(repo, base, head), cache_dir, offline)
ahead = _commits_ahead(forward, repo.family)
if ahead is None:
return None
if repo.family == "github":
behind = forward.get("behind_by") if isinstance(forward, dict) else None
else:
behind = _commits_ahead(
cached_api(_compare_url(repo, head, base), cache_dir, offline), repo.family
)
return (ahead, behind) if isinstance(behind, int) else None
def find_renamed(result: CompareResult, path: str) -> str | None:
"""New path of a file the comparison reports as renamed."""
for change in result.files:
if change.status == "renamed" and change.previous_path == path:
return change.path
return None
def _tree_url(repo: Repo, sha: str) -> str | None:
if repo.family == "gitlab":
return None
return f"{repo.api_base}/repos/{repo.slug}/git/trees/{sha}?recursive=1"
def list_directory(
repo: Repo, sha: str, path: str, cache_dir: str, offline: bool = False
) -> list[str] | None:
"""Names of the blobs directly under one directory at one revision.
One request for the directory alone, where the whole tree of a large
repository comes back truncated. None when the forge has no such call
or the directory does not exist there.
"""
if repo.family != "github":
return None
url = f"{repo.api_base}/repos/{repo.slug}/git/trees/{sha}:{path.strip('/')}"
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, dict) or payload.get("truncated"):
return None
return sorted(
entry["path"]
for entry in payload.get("tree") or []
if isinstance(entry, dict) and entry.get("type") == "blob" and entry.get("path")
)
TREE_PAGE_SIZE = 100
MAX_TREE_PAGES = 50
def gitlab_tree_entries(
repo: Repo, sha: str, cache_dir: str, offline: bool, *,
path: str | None = None, recursive: bool = True,
) -> tuple[list[dict], bool]:
"""The entries of a GitLab tree at a revision, and whether the listing
is truncated. GitLab serves its tree in pages, each page cached on its
own URL.
A page that cannot be read mid-walk, or the page cap, reports the
listing as truncated: the entries already collected are real, but an
absence proves nothing.
"""
entries: list[dict] = []
scope = "" if path is None else f"&path={path}"
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{project_path(repo)}/repository/tree"
f"?ref={sha}{scope}&recursive={'true' if recursive else 'false'}"
f"&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
return entries, True
entries.extend(entry for entry in payload if isinstance(entry, dict))
if len(payload) < TREE_PAGE_SIZE:
return entries, False
return entries, True
def cache_gitlab_directory(
repo: Repo, sha: str, directory: str, cache_dir: str, offline: bool = False
) -> set[str] | None:
"""Every file under one GitLab directory, cached from one request.
GitLab counts anonymous requests per IP: reading Recalbox's hundred
system.ini files one raw URL at a time ran into HTTP 429 before the
end. The archive endpoint serves the directory in one request, and when
the API itself is refused, a shallow sparse git fetch does, since GitLab
does not count git traffic against that quota. Each file goes to the
cache `fetch_file` reads, and the list of paths is kept so a later run,
offline included, knows what is absent. None when the list is not
known (offline, never fetched).
"""
directory = directory.strip("/")
index = cache_path(cache_dir, repo, sha, f".archives/{directory}.json")
if index.is_file():
return set(json.loads(index.read_text(encoding="utf-8")))
if run_is_offline(offline) or repo.family != "gitlab":
return None
try:
files = _gitlab_archive_files(repo, sha, directory)
except RateLimitError:
files = _sparse_git_files(repo, sha, directory, cache_dir)
if not files:
raise UpstreamError(f"{repo.slug}@{sha[:8]}: nothing under {directory}")
for path, text in files.items():
write_cache(cache_path(cache_dir, repo, sha, path), text)
write_cache(index, json.dumps(sorted(files)))
return set(files)
def _gitlab_archive_files(repo: Repo, sha: str, directory: str) -> dict[str, str]:
url = (
f"{repo.api_base}/projects/{project_path(repo)}/repository/archive.tar.gz"
f"?sha={sha}&path={urllib.parse.quote(directory)}"
)
body = fetch_body(url)
if body is None:
return {}
prefix = directory + "/"
files: dict[str, str] = {}
with tarfile.open(fileobj=io.BytesIO(body), mode="r:gz") as archive:
for member in archive:
if not member.isfile():
continue
# The archive wraps everything in one <project>-<sha>-<path> folder.
inner = member.name.split("/", 1)[-1]
handle = archive.extractfile(member) if inner.startswith(prefix) else None
if handle is not None:
files[inner] = handle.read().decode("utf-8", errors="replace")
return files
def _sparse_git_files(repo: Repo, sha: str, directory: str, cache_dir: str) -> dict[str, str]:
"""One directory at one commit through git: depth 1, blobs of that
directory only, in a scratch work tree removed afterwards."""
url = f"https://{repo.host}/{repo.slug}.git"
Path(cache_dir).mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(dir=cache_dir, prefix=".sparse-"))
try:
steps = (
["init", "--quiet"],
["remote", "add", "origin", url],
["sparse-checkout", "set", "--no-cone", f"/{directory}/"],
["fetch", "--quiet", "--depth", "1", "--filter=blob:none", "origin", sha],
["checkout", "--quiet", "FETCH_HEAD"],
)
for argv in steps:
result = _git(argv, work)
if result.returncode:
raise UpstreamError(f"{url}: git {argv[0]} failed: {result.stderr.strip()}")
root = work / directory
return {
f"{directory}/{p.relative_to(root).as_posix()}": p.read_text(encoding="utf-8", errors="replace")
for p in sorted(root.rglob("*")) if p.is_file()
}
finally:
shutil.rmtree(work, ignore_errors=True)
def _tree_entries(
repo: Repo, sha: str, cache_dir: str, offline: bool
) -> tuple[list[dict], bool] | None:
"""Every entry of the tree at one revision, and whether the forge served
it in part. None when the forge serves no tree for it."""
if repo.family == "gitlab":
return gitlab_tree_entries(repo, sha, cache_dir, offline)
url = _tree_url(repo, sha)
if url is None:
return None
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, dict):
return None
entries = list(payload.get("tree") or [])
truncated = bool(payload.get("truncated"))
# Forgejo pages a recursive tree, 1000 entries at a time, and says how
# many there are: mirrors/Ryujinx holds 4704, and read as one page every
# citation past the first thousand was unverifiable. GitHub reports no
# count, its truncation is final.
total = payload.get("total_count")
if truncated and repo.family == "forgejo" and isinstance(total, int):
for page in range(2, MAX_TREE_PAGES + 1):
if len(entries) >= total:
break
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"])
truncated = len(entries) < total
return [entry for entry in entries if isinstance(entry, dict)], truncated
def list_tree(
repo: Repo, sha: str, cache_dir: str, offline: bool = False
) -> tuple[list[str], bool]:
"""Every blob path at one revision, and whether the forge truncated it."""
listing = _tree_entries(repo, sha, cache_dir, offline)
if listing is None:
return [], True
entries, truncated = listing
paths = [
entry["path"] for entry in entries
if entry.get("type") == "blob" and entry.get("path")
]
return paths, truncated
def list_gitlinks(
repo: Repo, sha: str, cache_dir: str, offline: bool = False
) -> dict[str, str]:
"""Submodule path -> the commit it points at, at one revision.
Read from the same tree listing as list_tree, so the call costs nothing
once the tree is cached. A listing the forge served in part raises
TruncatedListingError: a partial answer read as "no submodule there",
and a port then lost the upstream commit its gitlink pins.
"""
listing = _tree_entries(repo, sha, cache_dir, offline)
if listing is None:
return {}
entries, truncated = listing
if truncated:
raise TruncatedListingError(f"{repo.slug}@{sha[:8]}: tree listing truncated")
# GitLab names the target commit `id`, GitHub and Forgejo `sha`.
key = "id" if repo.family == "gitlab" else "sha"
return {
entry["path"]: entry[key]
for entry in entries
if entry.get("type") == "commit" and entry.get("path") and entry.get(key)
}
def submodule_urls(text: str, base: Repo) -> dict[str, Repo]:
"""Submodule path -> repository, read from a .gitmodules text.
A relative url (`../xash3d-fwgs.git`) names a sibling of the repository
that declares it, on the same forge.
"""
repos: dict[str, Repo] = {}
path = url = None
for line in [*text.splitlines(), "[end]"]:
stripped = line.strip()
if stripped.startswith("["):
if path and url:
if url.startswith(("../", "./")):
segments = [base.owner, base.name]
for part in url.split("/"):
if part == "..":
segments.pop()
elif part not in (".", ""):
segments.append(part)
url = f"https://{base.host}/{'/'.join(segments)}"
repo = parse_repo(url)
if repo is not None:
repos[path] = repo
path = url = None
continue
key, _, value = stripped.partition("=")
if key.strip() == "path":
path = value.strip()
elif key.strip() == "url":
url = value.strip()
return repos
def through_gitlink(
repo: Repo, sha: str, path: str, cache_dir: str, offline: bool = False
) -> tuple[Repo, str, str] | None:
"""The submodule repository, commit and inner path a path falls under.
starship cites `Torch src/Companion.cpp`, a file of the Torch submodule:
the declared tree holds only the gitlink, which pins the revision.
"""
links = list_gitlinks(repo, sha, cache_dir, offline)
link = next((p for p in links if path.startswith(p + "/")), None)
if link is None:
return None
modules = fetch_file(repo, sha, ".gitmodules", cache_dir, offline)
target = submodule_urls("\n".join(modules or ()), repo).get(link)
if target is None:
return None
return target, links[link], path[len(link) + 1:]
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":
@@ -1421,104 +667,3 @@ def commits_touching(
1 for entry in payload
if isinstance(entry, dict) and (entry.get("sha") or entry.get("id")) != base
)
# Commit graphs kept to count the commits between a tag and a pin. A
# treeless bare clone holds commits and tags only: the files a profile reads
# come from fetch_file, by sha.
GIT_DIR = "_git"
def clone_dir(cache_dir: str, repo: Repo) -> Path:
"""Where the commit graph of a repository is kept."""
return Path(cache_dir) / GIT_DIR / repo.host / repo.owner / f"{repo.name}.git"
def _git(args: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0")
return subprocess.run(
["git", *args], cwd=cwd, capture_output=True, text=True, env=env, check=False
)
def _has_commit(clone: Path, sha: str) -> bool:
return _git(["cat-file", "-e", f"{sha}^{{commit}}"], clone).returncode == 0
def _graph(repo: Repo, sha: str, cache_dir: str, offline: bool) -> Path:
"""A clone holding sha and every tag, fetched again once tags may have moved."""
offline = run_is_offline(offline)
clone = clone_dir(cache_dir, repo)
url = f"https://{repo.host}/{repo.slug}.git"
if not (clone / "HEAD").is_file():
if offline:
raise NotCachedError(f"{repo.slug}: no commit graph in the offline cache")
clone.parent.mkdir(parents=True, exist_ok=True)
result = _git(["clone", "--quiet", "--bare", "--filter=tree:0", url, str(clone)])
if result.returncode:
raise UpstreamError(f"{url}: clone failed: {result.stderr.strip()}")
_git(["fetch", "--quiet", "--filter=tree:0", "--tags", "origin"], clone)
stamp = clone / "FETCH_HEAD"
fresh = stamp.is_file() and time.time() - stamp.stat().st_mtime <= MOVING_TTL
if offline or (fresh and _has_commit(clone, sha)):
if not _has_commit(clone, sha):
raise NotCachedError(f"{repo.slug}@{sha[:8]}: not in the offline commit graph")
return clone
# Tags are fetched again: a tag pushed since the clone can be nearer.
result = _git(
["fetch", "--quiet", "--filter=tree:0", "--force", "--tags", "origin",
"+refs/heads/*:refs/heads/*"], clone,
)
if result.returncode:
raise UpstreamError(f"{url}: fetch failed: {result.stderr.strip()}")
if not _has_commit(clone, sha):
# A commit no branch reaches any more: a rewritten fork, a PR head.
_git(["fetch", "--quiet", "--filter=tree:0", "origin", sha], clone)
if not _has_commit(clone, sha):
raise UpstreamError(f"{url}: {sha[:8]} is on no branch the forge serves")
return clone
def describe(
repo: Repo, sha: str, cache_dir: str, offline: bool = False,
match: str | None = None,
) -> tuple[str, int] | None:
"""The tag nearest to sha in its history, and the commits after it.
git describe counts the commits sha has that the tag lacks, the count a
forge compare reports as ahead. ``match`` is a glob the tag must fit.
None when no tag is reachable from sha.
"""
clone = _graph(repo, sha, cache_dir, offline)
argv = ["describe", "--tags", "--long", "--abbrev=40"]
if match:
argv += ["--match", match]
result = _git([*argv, sha], clone)
if result.returncode:
if any(text in result.stderr for text in (
"No names found", "No tags can describe", "cannot describe",
)):
return None
raise UpstreamError(f"{repo.slug}: describe {sha[:8]}: {result.stderr.strip()}")
tag, _distance, _commit = result.stdout.strip().rsplit("-", 2)
# describe's own count is an estimate across merges (ares: 149 where the
# pin holds 143 commits the tag lacks): the exact count is rev-list's.
counted = _git(["rev-list", "--count", f"refs/tags/{tag}..{sha}"], clone)
if counted.returncode:
raise UpstreamError(f"{repo.slug}: {tag}..{sha[:8]}: {counted.stderr.strip()}")
return tag, int(counted.stdout.strip())
def graph_ancestry(
repo: Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> tuple[int, int]:
"""(ahead, behind) counted in the commit graph, for a pair a forge
refuses to compare (GitHub answers 422 past a diff size)."""
clone = _graph(repo, head, cache_dir, offline)
counts = []
for spec in (f"{base}..{head}", f"{head}..{base}"):
result = _git(["rev-list", "--count", spec], clone)
if result.returncode:
raise UpstreamError(f"{repo.slug}: {spec}: {result.stderr.strip()}")
counts.append(int(result.stdout.strip()))
return counts[0], counts[1]
+522
View File
@@ -0,0 +1,522 @@
"""Trees of upstream revisions: what changed between two, listings, gitlinks and local clone history."""
from __future__ import annotations
import io
import json
import os
import shutil
import subprocess
import tarfile
import tempfile
import time
import urllib.parse
from dataclasses import dataclass
from pathlib import Path
from core import forgehttp, upstream
from core.offline import run_is_offline
GITHUB_COMPARE_CAP = 300
@dataclass(frozen=True)
class FileChange:
status: str
path: str
previous_path: str | None
@dataclass(frozen=True)
class CompareResult:
files: list[FileChange]
truncated: bool
# The forge reports the two revisions on separate lines of history: the
# base is no ancestor of the head. A pin in that state survives only
# while the forge keeps the orphaned object (advancemame, 2026-10-05).
diverged: bool = False
def _compare_url(repo: upstream.Repo, base: str, head: str) -> str:
if repo.family == "gitlab":
return (
f"{repo.api_base}/projects/{upstream.project_path(repo)}"
f"/repository/compare?from={base}&to={head}"
)
return f"{repo.api_base}/repos/{repo.slug}/compare/{base}...{head}"
def _changes_from_github(payload: dict) -> list[FileChange]:
return [
FileChange(
entry.get("status", "modified"),
entry.get("filename", ""),
entry.get("previous_filename"),
)
for entry in (payload.get("files") or [])
if isinstance(entry, dict)
]
def _changes_from_gitlab(payload: dict) -> list[FileChange]:
changes = []
for entry in payload.get("diffs") or []:
if not isinstance(entry, dict):
continue
if entry.get("renamed_file"):
status = "renamed"
elif entry.get("new_file"):
status = "added"
elif entry.get("deleted_file"):
status = "removed"
else:
status = "modified"
previous = entry.get("old_path") if status == "renamed" else None
changes.append(FileChange(status, entry.get("new_path", ""), previous))
return changes
def compare(
repo: upstream.Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> CompareResult:
"""Tree difference between two revisions."""
payload = upstream.cached_api(_compare_url(repo, base, head), cache_dir, offline)
if not isinstance(payload, dict):
return CompareResult([], True)
if repo.family == "gitlab":
files = _changes_from_gitlab(payload)
else:
files = _changes_from_github(payload)
truncated = bool(payload.get("truncated")) or len(files) >= GITHUB_COMPARE_CAP
return CompareResult(files, truncated, payload.get("status") == "diverged")
def _commits_ahead(payload: object, family: str) -> int | None:
"""Commits the compare head carries that its base does not."""
if not isinstance(payload, dict):
return None
if family == "github":
value = payload.get("ahead_by")
elif family == "gitlab":
value = len(payload.get("commits") or [])
else:
value = payload.get("total_commits")
return value if isinstance(value, int) else None
def fork_base(
repo: upstream.Repo, sha: str, fork: upstream.Repo, fork_sha: str, cache_dir: str,
offline: bool = False,
) -> str | None:
"""The commit of ``repo`` that ``fork`` at ``fork_sha`` has merged up to.
GitHub compares across a fork network and names the merge base. Two
repositories outside one network answer 404, and None is returned.
"""
if repo.family != "github" or fork.family != "github":
return None
payload = upstream.cached_api(
f"{repo.api_base}/repos/{repo.slug}/compare/"
f"{sha}...{fork.owner}:{fork.name}:{fork_sha}",
cache_dir, offline,
)
base = payload.get("merge_base_commit") if isinstance(payload, dict) else None
return base.get("sha") if isinstance(base, dict) else None
def ancestry(
repo: upstream.Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> tuple[int, int] | None:
"""(ahead, behind): commits head has that base lacks, and the reverse.
Two shas never change their history, so both answers are cached for
good. GitHub gives both counts in one answer, GitLab and Forgejo list
one direction only and are asked twice.
"""
forward = upstream.cached_api(_compare_url(repo, base, head), cache_dir, offline)
ahead = _commits_ahead(forward, repo.family)
if ahead is None:
return None
if repo.family == "github":
behind = forward.get("behind_by") if isinstance(forward, dict) else None
else:
behind = _commits_ahead(
upstream.cached_api(_compare_url(repo, head, base), cache_dir, offline), repo.family
)
return (ahead, behind) if isinstance(behind, int) else None
def find_renamed(result: CompareResult, path: str) -> str | None:
"""New path of a file the comparison reports as renamed."""
for change in result.files:
if change.status == "renamed" and change.previous_path == path:
return change.path
return None
def _tree_url(repo: upstream.Repo, sha: str) -> str | None:
if repo.family == "gitlab":
return None
return f"{repo.api_base}/repos/{repo.slug}/git/trees/{sha}?recursive=1"
def list_directory(
repo: upstream.Repo, sha: str, path: str, cache_dir: str, offline: bool = False
) -> list[str] | None:
"""Names of the blobs directly under one directory at one revision.
One request for the directory alone, where the whole tree of a large
repository comes back truncated. None when the forge has no such call
or the directory does not exist there.
"""
if repo.family != "github":
return None
url = f"{repo.api_base}/repos/{repo.slug}/git/trees/{sha}:{path.strip('/')}"
payload = upstream.cached_api(url, cache_dir, offline)
if not isinstance(payload, dict) or payload.get("truncated"):
return None
return sorted(
entry["path"]
for entry in payload.get("tree") or []
if isinstance(entry, dict) and entry.get("type") == "blob" and entry.get("path")
)
TREE_PAGE_SIZE = 100
MAX_TREE_PAGES = 50
def gitlab_tree_entries(
repo: upstream.Repo, sha: str, cache_dir: str, offline: bool, *,
path: str | None = None, recursive: bool = True,
) -> tuple[list[dict], bool]:
"""The entries of a GitLab tree at a revision, and whether the listing
is truncated. GitLab serves its tree in pages, each page cached on its
own URL.
A page that cannot be read mid-walk, or the page cap, reports the
listing as truncated: the entries already collected are real, but an
absence proves nothing.
"""
entries: list[dict] = []
scope = "" if path is None else f"&path={path}"
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{upstream.project_path(repo)}/repository/tree"
f"?ref={sha}{scope}&recursive={'true' if recursive else 'false'}"
f"&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = upstream.cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
return entries, True
entries.extend(entry for entry in payload if isinstance(entry, dict))
if len(payload) < TREE_PAGE_SIZE:
return entries, False
return entries, True
def cache_gitlab_directory(
repo: upstream.Repo, sha: str, directory: str, cache_dir: str, offline: bool = False
) -> set[str] | None:
"""Every file under one GitLab directory, cached from one request.
GitLab counts anonymous requests per IP: reading Recalbox's hundred
system.ini files one raw URL at a time ran into HTTP 429 before the
end. The archive endpoint serves the directory in one request, and when
the API itself is refused, a shallow sparse git fetch does, since GitLab
does not count git traffic against that quota. Each file goes to the
cache `fetch_file` reads, and the list of paths is kept so a later run,
offline included, knows what is absent. None when the list is not
known (offline, never fetched).
"""
directory = directory.strip("/")
index = upstream.cache_path(cache_dir, repo, sha, f".archives/{directory}.json")
if index.is_file():
return set(json.loads(index.read_text(encoding="utf-8")))
if run_is_offline(offline) or repo.family != "gitlab":
return None
try:
files = _gitlab_archive_files(repo, sha, directory)
except forgehttp.RateLimitError:
files = _sparse_git_files(repo, sha, directory, cache_dir)
if not files:
raise forgehttp.UpstreamError(f"{repo.slug}@{sha[:8]}: nothing under {directory}")
for path, text in files.items():
upstream.write_cache(upstream.cache_path(cache_dir, repo, sha, path), text)
upstream.write_cache(index, json.dumps(sorted(files)))
return set(files)
def _gitlab_archive_files(repo: upstream.Repo, sha: str, directory: str) -> dict[str, str]:
url = (
f"{repo.api_base}/projects/{upstream.project_path(repo)}/repository/archive.tar.gz"
f"?sha={sha}&path={urllib.parse.quote(directory)}"
)
body = forgehttp.fetch_body(url)
if body is None:
return {}
prefix = directory + "/"
files: dict[str, str] = {}
with tarfile.open(fileobj=io.BytesIO(body), mode="r:gz") as archive:
for member in archive:
if not member.isfile():
continue
# The archive wraps everything in one <project>-<sha>-<path> folder.
inner = member.name.split("/", 1)[-1]
handle = archive.extractfile(member) if inner.startswith(prefix) else None
if handle is not None:
files[inner] = handle.read().decode("utf-8", errors="replace")
return files
def _sparse_git_files(repo: upstream.Repo, sha: str, directory: str, cache_dir: str) -> dict[str, str]:
"""One directory at one commit through git: depth 1, blobs of that
directory only, in a scratch work tree removed afterwards."""
url = f"https://{repo.host}/{repo.slug}.git"
Path(cache_dir).mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(dir=cache_dir, prefix=".sparse-"))
try:
steps = (
["init", "--quiet"],
["remote", "add", "origin", url],
["sparse-checkout", "set", "--no-cone", f"/{directory}/"],
["fetch", "--quiet", "--depth", "1", "--filter=blob:none", "origin", sha],
["checkout", "--quiet", "FETCH_HEAD"],
)
for argv in steps:
result = _git(argv, work)
if result.returncode:
raise forgehttp.UpstreamError(f"{url}: git {argv[0]} failed: {result.stderr.strip()}")
root = work / directory
return {
f"{directory}/{p.relative_to(root).as_posix()}": p.read_text(encoding="utf-8", errors="replace")
for p in sorted(root.rglob("*")) if p.is_file()
}
finally:
shutil.rmtree(work, ignore_errors=True)
def _tree_entries(
repo: upstream.Repo, sha: str, cache_dir: str, offline: bool
) -> tuple[list[dict], bool] | None:
"""Every entry of the tree at one revision, and whether the forge served
it in part. None when the forge serves no tree for it."""
if repo.family == "gitlab":
return gitlab_tree_entries(repo, sha, cache_dir, offline)
url = _tree_url(repo, sha)
if url is None:
return None
payload = upstream.cached_api(url, cache_dir, offline)
if not isinstance(payload, dict):
return None
entries = list(payload.get("tree") or [])
truncated = bool(payload.get("truncated"))
# Forgejo pages a recursive tree, 1000 entries at a time, and says how
# many there are: mirrors/Ryujinx holds 4704, and read as one page every
# citation past the first thousand was unverifiable. GitHub reports no
# count, its truncation is final.
total = payload.get("total_count")
if truncated and repo.family == "forgejo" and isinstance(total, int):
for page in range(2, MAX_TREE_PAGES + 1):
if len(entries) >= total:
break
more = upstream.cached_api(f"{url}&page={page}", cache_dir, offline)
if not isinstance(more, dict) or not more.get("tree"):
break
entries.extend(more["tree"])
truncated = len(entries) < total
return [entry for entry in entries if isinstance(entry, dict)], truncated
def list_tree(
repo: upstream.Repo, sha: str, cache_dir: str, offline: bool = False
) -> tuple[list[str], bool]:
"""Every blob path at one revision, and whether the forge truncated it."""
listing = _tree_entries(repo, sha, cache_dir, offline)
if listing is None:
return [], True
entries, truncated = listing
paths = [
entry["path"] for entry in entries
if entry.get("type") == "blob" and entry.get("path")
]
return paths, truncated
def list_gitlinks(
repo: upstream.Repo, sha: str, cache_dir: str, offline: bool = False
) -> dict[str, str]:
"""Submodule path -> the commit it points at, at one revision.
Read from the same tree listing as list_tree, so the call costs nothing
once the tree is cached. A listing the forge served in part raises
TruncatedListingError: a partial answer read as "no submodule there",
and a port then lost the upstream commit its gitlink pins.
"""
listing = _tree_entries(repo, sha, cache_dir, offline)
if listing is None:
return {}
entries, truncated = listing
if truncated:
raise forgehttp.TruncatedListingError(f"{repo.slug}@{sha[:8]}: tree listing truncated")
# GitLab names the target commit `id`, GitHub and Forgejo `sha`.
key = "id" if repo.family == "gitlab" else "sha"
return {
entry["path"]: entry[key]
for entry in entries
if entry.get("type") == "commit" and entry.get("path") and entry.get(key)
}
def submodule_urls(text: str, base: upstream.Repo) -> dict[str, upstream.Repo]:
"""Submodule path -> repository, read from a .gitmodules text.
A relative url (`../xash3d-fwgs.git`) names a sibling of the repository
that declares it, on the same forge.
"""
repos: dict[str, upstream.Repo] = {}
path = url = None
for line in [*text.splitlines(), "[end]"]:
stripped = line.strip()
if stripped.startswith("["):
if path and url:
if url.startswith(("../", "./")):
segments = [base.owner, base.name]
for part in url.split("/"):
if part == "..":
segments.pop()
elif part not in (".", ""):
segments.append(part)
url = f"https://{base.host}/{'/'.join(segments)}"
repo = upstream.parse_repo(url)
if repo is not None:
repos[path] = repo
path = url = None
continue
key, _, value = stripped.partition("=")
if key.strip() == "path":
path = value.strip()
elif key.strip() == "url":
url = value.strip()
return repos
def through_gitlink(
repo: upstream.Repo, sha: str, path: str, cache_dir: str, offline: bool = False
) -> tuple[upstream.Repo, str, str] | None:
"""The submodule repository, commit and inner path a path falls under.
starship cites `Torch src/Companion.cpp`, a file of the Torch submodule:
the declared tree holds only the gitlink, which pins the revision.
"""
links = list_gitlinks(repo, sha, cache_dir, offline)
link = next((p for p in links if path.startswith(p + "/")), None)
if link is None:
return None
modules = upstream.fetch_file(repo, sha, ".gitmodules", cache_dir, offline)
target = submodule_urls("\n".join(modules or ()), repo).get(link)
if target is None:
return None
return target, links[link], path[len(link) + 1:]
# Commit graphs kept to count the commits between a tag and a pin. A
# treeless bare clone holds commits and tags only: the files a profile reads
# come from fetch_file, by sha.
GIT_DIR = "_git"
def clone_dir(cache_dir: str, repo: upstream.Repo) -> Path:
"""Where the commit graph of a repository is kept."""
return Path(cache_dir) / GIT_DIR / repo.host / repo.owner / f"{repo.name}.git"
def _git(args: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0")
return subprocess.run(
["git", *args], cwd=cwd, capture_output=True, text=True, env=env, check=False
)
def _has_commit(clone: Path, sha: str) -> bool:
return _git(["cat-file", "-e", f"{sha}^{{commit}}"], clone).returncode == 0
def _graph(repo: upstream.Repo, sha: str, cache_dir: str, offline: bool) -> Path:
"""A clone holding sha and every tag, fetched again once tags may have moved."""
offline = run_is_offline(offline)
clone = clone_dir(cache_dir, repo)
url = f"https://{repo.host}/{repo.slug}.git"
if not (clone / "HEAD").is_file():
if offline:
raise forgehttp.NotCachedError(f"{repo.slug}: no commit graph in the offline cache")
clone.parent.mkdir(parents=True, exist_ok=True)
result = _git(["clone", "--quiet", "--bare", "--filter=tree:0", url, str(clone)])
if result.returncode:
raise forgehttp.UpstreamError(f"{url}: clone failed: {result.stderr.strip()}")
_git(["fetch", "--quiet", "--filter=tree:0", "--tags", "origin"], clone)
stamp = clone / "FETCH_HEAD"
fresh = stamp.is_file() and time.time() - stamp.stat().st_mtime <= upstream.MOVING_TTL
if offline or (fresh and _has_commit(clone, sha)):
if not _has_commit(clone, sha):
raise forgehttp.NotCachedError(f"{repo.slug}@{sha[:8]}: not in the offline commit graph")
return clone
# Tags are fetched again: a tag pushed since the clone can be nearer.
result = _git(
["fetch", "--quiet", "--filter=tree:0", "--force", "--tags", "origin",
"+refs/heads/*:refs/heads/*"], clone,
)
if result.returncode:
raise forgehttp.UpstreamError(f"{url}: fetch failed: {result.stderr.strip()}")
if not _has_commit(clone, sha):
# A commit no branch reaches any more: a rewritten fork, a PR head.
_git(["fetch", "--quiet", "--filter=tree:0", "origin", sha], clone)
if not _has_commit(clone, sha):
raise forgehttp.UpstreamError(f"{url}: {sha[:8]} is on no branch the forge serves")
return clone
def describe(
repo: upstream.Repo, sha: str, cache_dir: str, offline: bool = False,
match: str | None = None,
) -> tuple[str, int] | None:
"""The tag nearest to sha in its history, and the commits after it.
git describe counts the commits sha has that the tag lacks, the count a
forge compare reports as ahead. ``match`` is a glob the tag must fit.
None when no tag is reachable from sha.
"""
clone = _graph(repo, sha, cache_dir, offline)
argv = ["describe", "--tags", "--long", "--abbrev=40"]
if match:
argv += ["--match", match]
result = _git([*argv, sha], clone)
if result.returncode:
if any(text in result.stderr for text in (
"No names found", "No tags can describe", "cannot describe",
)):
return None
raise forgehttp.UpstreamError(f"{repo.slug}: describe {sha[:8]}: {result.stderr.strip()}")
tag, _distance, _commit = result.stdout.strip().rsplit("-", 2)
# describe's own count is an estimate across merges (ares: 149 where the
# pin holds 143 commits the tag lacks): the exact count is rev-list's.
counted = _git(["rev-list", "--count", f"refs/tags/{tag}..{sha}"], clone)
if counted.returncode:
raise forgehttp.UpstreamError(f"{repo.slug}: {tag}..{sha[:8]}: {counted.stderr.strip()}")
return tag, int(counted.stdout.strip())
def graph_ancestry(
repo: upstream.Repo, base: str, head: str, cache_dir: str, offline: bool = False
) -> tuple[int, int]:
"""(ahead, behind) counted in the commit graph, for a pair a forge
refuses to compare (GitHub answers 422 past a diff size)."""
clone = _graph(repo, head, cache_dir, offline)
counts = []
for spec in (f"{base}..{head}", f"{head}..{base}"):
result = _git(["rev-list", "--count", spec], clone)
if result.returncode:
raise forgehttp.UpstreamError(f"{repo.slug}: {spec}: {result.stderr.strip()}")
counts.append(int(result.stdout.strip()))
return counts[0], counts[1]
+1 -1
View File
@@ -28,7 +28,7 @@ from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core.paths import REPO_ROOT
from core.upstream import UpstreamError
from core.forgehttp import UpstreamError
from core.ziptools import safe_extract_zip
from model.releaserecord import RECORD, load_record
from release.downloaderror import DownloadError
+2 -1
View File
@@ -24,6 +24,7 @@ import sys
sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from core import forgehttp
from core.cli import add_repo_inputs, require_directory
from model.profiles import ProfileSelectionError, load_emulator_profiles, resolve_profile_name
from profiling import fileless
@@ -65,7 +66,7 @@ def main() -> None:
for name in names:
try:
hits = fileless.audit(name, args.emulators_dir, args.cache_dir, args.offline)
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
print(f"{name}: unreachable, {exc}", file=sys.stderr)
unreachable += 1
continue
+5 -4
View File
@@ -10,6 +10,7 @@ from datetime import datetime, timezone
from pathlib import Path
from core import upstream
from core import forgehttp
from core.paths import REPO_ROOT
from scripts.scraper import game_dat_importer
from scripts.scraper.dat_fetch import is_tracked_dat, label_version
@@ -109,7 +110,7 @@ def redump_datfile_version(code: str) -> str:
gives the download: a HEAD request, nothing downloaded."""
url = game_dat_importer.REDUMP_DATFILE_URL.format(code=code)
request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "retrobios/1.0"})
disposition = upstream.open_retrying(
disposition = forgehttp.open_retrying(
request, lambda response: response.headers.get("Content-Disposition", ""), timeout=60
)
version = game_dat_importer.served_version(game_dat_importer.datfile_name(disposition) or "")
@@ -135,7 +136,7 @@ def _check_redump_games(offline: bool) -> Finding:
for code, (_name, system, _floor) in sorted(game_dat_importer.REDUMP_DATS.items()):
try:
remote = redump_datfile_version(code)
except (OSError, http.client.HTTPException, upstream.UpstreamError, ValueError) as exc:
except (OSError, http.client.HTTPException, forgehttp.UpstreamError, ValueError) as exc:
return Finding("catalogs", subject, UNKNOWN, local=newest, detail=str(exc))
remote_newest = max(remote_newest, remote)
if local.get(system) != remote:
@@ -194,8 +195,8 @@ def _check_tosec(offline: bool) -> Finding:
if offline:
return Finding("catalogs", "tosec", SKIPPED, local=imported, detail="offline")
try:
html = upstream.http_text(TOSEC_DOWNLOADS)
except upstream.UpstreamError as exc:
html = forgehttp.http_text(TOSEC_DOWNLOADS)
except forgehttp.UpstreamError as exc:
return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail=str(exc))
latest = tosec_latest_pack(html or "")
if latest is None:
+5 -4
View File
@@ -6,6 +6,7 @@ import json
import re
from core import upstream
from core import forgehttp
from core.paths import REPO_ROOT
from installer_build import pins as installer_build_pins
from freshness.findings import INSTALLER_PIN, OK, SKIPPED, STALE, UNKNOWN, Finding
@@ -76,7 +77,7 @@ def specifier_allows(spec: str, version: str) -> bool:
def pypi_latest(name: str) -> str | None:
payload = upstream.http_json(PYPI_URL.format(name=name))
payload = forgehttp.http_json(PYPI_URL.format(name=name))
if not isinstance(payload, dict):
return None
info = payload.get("info") or {}
@@ -93,7 +94,7 @@ def parse_npm_pins(text: str) -> dict[str, str]:
def npm_latest(name: str) -> str | None:
payload = upstream.http_json(NPM_URL.format(name=name))
payload = forgehttp.http_json(NPM_URL.format(name=name))
if not isinstance(payload, dict):
return None
return str(payload.get("version") or "") or None
@@ -110,7 +111,7 @@ def _npm_findings() -> list[Finding]:
continue
try:
latest = npm_latest(name)
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
findings.append(Finding("ci", subject, UNKNOWN, local=pinned, detail=str(exc)))
continue
if latest is None:
@@ -147,7 +148,7 @@ def check_ci(cache_dir: str, offline: bool) -> list[Finding]:
for name, spec in sorted(pins.items()):
try:
latest = pypi_latest(name)
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
findings.append(Finding("ci", f"pypi:{name}", UNKNOWN, local=spec, detail=str(exc)))
continue
if latest is None:
+6 -4
View File
@@ -6,6 +6,8 @@ import re
from pathlib import Path
from core import upstream
from core import forgehttp
from core import upstreamtree
from model.sourcerevision import scraped_revision
from freshness.findings import OK, SHOWN_NAMES, SKIPPED, STALE, UNKNOWN, Finding
@@ -89,17 +91,17 @@ def check_pin_builds(
# platform's tree pins: KNULLI builds Batocera's
# amiberry package through its batocera submodule.
modules = upstream.fetch_file(repo, at, ".gitmodules", cache_dir, offline)
declared = upstream.submodule_urls("\n".join(modules or ()), repo)
declared = upstreamtree.submodule_urls("\n".join(modules or ()), repo)
if any(reference["path"].startswith(f"{p}/") for p in declared):
linked = upstream.through_gitlink(repo, at, reference["path"],
linked = upstreamtree.through_gitlink(repo, at, reference["path"],
cache_dir, offline)
if linked is not None:
lines = upstream.fetch_file(*linked, cache_dir, offline)
except upstream.NotCachedError:
except forgehttp.NotCachedError:
findings.append(Finding("profiles", subject, SKIPPED, local=recorded[:12],
detail="offline, the build file is not cached"))
continue
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
findings.append(Finding("profiles", subject, UNKNOWN, local=recorded[:12],
detail=str(exc)))
continue
+3 -3
View File
@@ -7,7 +7,7 @@ import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from core import upstream
from core import forgehttp
from model.registry import list_registered_platforms, load_platform_registry
from model.sources import source_yaml_file
from freshness.findings import ERROR, OK, SKIPPED, STALE, UNKNOWN, Finding
@@ -96,9 +96,9 @@ def check_emulatorjs(platforms_dir: Path, offline: bool) -> Finding:
tag = str((source_yaml_file(platforms_dir / "romm.yml") or {}).get("version", ""))
for path in ROMM_DOCKERFILES:
try:
text = upstream.http_text(
text = forgehttp.http_text(
f"https://raw.githubusercontent.com/rommapp/romm/{tag}/{path}")
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
return Finding("platforms", subject, UNKNOWN, local=local, detail=str(exc))
pin = emulatorjs_pin(text or "")
if pin:
+2 -1
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
from pathlib import Path
from core import upstream
from core import upstreamtree
from model.registry import load_platform_registry
from model.romfolders import load_sources, row_sources, sources_dir
from model.sourcerevision import scraped_revision
@@ -115,6 +116,6 @@ def _romfolder_upstream(
return Finding("romfolders", subject, UNKNOWN, local=pin, detail="branch head unavailable")
if head == commit:
return Finding("romfolders", subject, OK, local=pin, detail="branch head")
counts = upstream.ancestry(repo, commit, head, cache_dir)
counts = upstreamtree.ancestry(repo, commit, head, cache_dir)
behind = f"{counts[0]} commits behind the branch head" if counts else "the branch head moved"
return Finding("romfolders", subject, STALE, local=pin, remote=head[:12], detail=behind)
+2 -1
View File
@@ -9,6 +9,7 @@ from datetime import datetime, timezone
from pathlib import Path
from core import upstream
from core import forgehttp
from model.profiles import upstream_profile_index
from model.sources import source_yaml_file
from model.targets import apply_target_overrides, platform_overrides, read_target_overrides
@@ -152,7 +153,7 @@ def check_lakka_release(platforms_dir: Path, cache_dir: str, offline: bool) -> F
repo = upstream.parse_repo(f"https://github.com/{LAKKA_REPO}")
try:
release = upstream.latest_release(repo, cache_dir) if repo else None
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
return Finding("targets", subject, UNKNOWN, local=local, detail=str(exc))
if release is None:
return Finding("targets", subject, UNKNOWN, local=local, detail="no release listed")
+2 -1
View File
@@ -25,6 +25,7 @@ import sys
sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from core import forgehttp
from core.cli import add_repo_inputs, require_directory
from profiling.mamerefs import audit, rewrite
@@ -54,7 +55,7 @@ def main() -> None:
findings, agreed, unjudged = audit(
name, args.emulators_dir, args.cache_dir, args.offline
)
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
print(f"{name}: unreachable, {exc}", file=sys.stderr)
continue
total += len(findings)
+8 -7
View File
@@ -22,6 +22,7 @@ from collections.abc import Iterable
from pathlib import Path
from core import upstream
from core import forgehttp
from core.artifacts import set_plain_mode
from core.hashing import compute_hashes, file_digest, parse_hash_list
from core.paths import REPO_ROOT
@@ -211,18 +212,18 @@ def restore_verified(source: str, path: str, sha1: str) -> bool:
os.unlink(scratch)
_FAILURES = (urllib.error.URLError, OSError, http.client.HTTPException, upstream.UpstreamError)
_FAILURES = (urllib.error.URLError, OSError, http.client.HTTPException, forgehttp.UpstreamError)
def _download(name: str, tmp_path: str) -> bool:
"""Stream the first release URL of *name* that answers into *tmp_path*,
each through core.upstream.download (scratch, rename, retries)."""
each through core.forgehttp.download (scratch, rename, retries)."""
# Only a name no candidate answers is reported: a spaced name is
# published dotted, and logging its first 404 read as a missing asset.
failures: list[str] = []
for candidate, url in _asset_urls(name):
try:
upstream.download(url, tmp_path, timeout=300, user_agent=USER_AGENT)
forgehttp.download(url, tmp_path, timeout=300, user_agent=USER_AGENT)
return True
except _FAILURES as exc:
# A stalled or cut stream is a timeout or IncompleteRead, not
@@ -434,9 +435,9 @@ def _served_digests() -> dict[str, str]:
f"{LARGE_FILES_RELEASE}"
)
try:
body = upstream.fetch_body(url, accept_json=True, timeout=60, user_agent=USER_AGENT)
body = forgehttp.fetch_body(url, accept_json=True, timeout=60, user_agent=USER_AGENT)
release = json.loads(body) if body is not None else {}
except (upstream.UpstreamError, ValueError) as exc:
except (forgehttp.UpstreamError, ValueError) as exc:
print(f" large files release listing: {exc}", file=sys.stderr)
return {}
digests = dict(digests_of(release.get("assets") or []))
@@ -448,10 +449,10 @@ def _served_size(name: str) -> int | None:
"""Size of the asset the release serves now, or None when unreadable."""
for candidate, url in _asset_urls(name):
req = urllib.request.Request(
url, method="HEAD", headers=upstream.forge_headers(url, user_agent=USER_AGENT)
url, method="HEAD", headers=forgehttp.forge_headers(url, user_agent=USER_AGENT)
)
try:
length = upstream.open_retrying(
length = forgehttp.open_retrying(
req, lambda resp: resp.headers.get("Content-Length"), 60
)
except _FAILURES as exc:
+9 -8
View File
@@ -16,8 +16,9 @@ from collections.abc import Callable, Iterator
from pathlib import Path
from core import upstream
from core import forgehttp
from core.artifacts import file_lock as _file_lock, write_text_atomic
from core.upstream import remote_etag as _get_remote_etag
from core.forgehttp import remote_etag as _get_remote_etag
from model.registry import load_versions, versions_file_for
from packs.datadirextract import extract_tar_subtree, extract_zip_tree
@@ -30,7 +31,7 @@ DOWNLOAD_TIMEOUT = 300
# A mirror sometimes answers with a page that is not the archive: the
# buildbot's ScummVM.zip failed CI once as "File is not a zip file" and
# downloaded fine minutes later. Seconds to wait before each retry. The
# transfer itself is retried by core.upstream.download: these waits cover
# transfer itself is retried by core.forgehttp.download: these waits cover
# an archive that arrived whole and does not read.
DOWNLOAD_RETRY_WAITS = (5, 20)
_TRANSIENT = (
@@ -182,7 +183,7 @@ def get_remote_sha(source_url: str, version: str) -> str | None:
return None
try:
return upstream.resolve_head(repo, None, branch=version)
except (upstream.UpstreamError, ValueError) as exc:
except (forgehttp.UpstreamError, ValueError) as exc:
log.warning("failed to fetch remote SHA for %s@%s: %s", repo.slug, version, exc)
return None
@@ -266,7 +267,7 @@ def _download_and_extract_zip(
def _fetch(source_url: str, archive_path: Path, measured: Callable[[int], None] | None) -> None:
"""Download source_url to archive_path, its size handed to measured."""
log.info("downloading %s", source_url)
upstream.download(
forgehttp.download(
source_url, archive_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT
)
if measured is not None:
@@ -277,7 +278,7 @@ def _measure_archive(source_url: str) -> int | None:
"""The size of the archive at source_url, read by streaming it: a
tarball GitHub builds on request is sent without a Content-Length."""
req = urllib.request.Request(
source_url, headers=upstream.forge_headers(source_url, user_agent=USER_AGENT)
source_url, headers=forgehttp.forge_headers(source_url, user_agent=USER_AGENT)
)
def count(resp: http.client.HTTPResponse) -> int:
@@ -287,8 +288,8 @@ def _measure_archive(source_url: str) -> int | None:
return size
try:
size = upstream.open_retrying(req, count, DOWNLOAD_TIMEOUT)
except (*_TRANSIENT, upstream.UpstreamError) as exc:
size = forgehttp.open_retrying(req, count, DOWNLOAD_TIMEOUT)
except (*_TRANSIENT, forgehttp.UpstreamError) as exc:
log.warning("could not measure %s: %s", source_url, exc)
return None
return size or None
@@ -446,7 +447,7 @@ def _refresh_entry(
try:
file_count = fetch()
break
except (NothingExtractedError, ValueError, upstream.UpstreamError) as exc:
except (NothingExtractedError, ValueError, forgehttp.UpstreamError) as exc:
# A host gone or still rate limited after core.upstream's own
# waits answers the same way on the next try.
log.warning("[%s] download failed: %s", key, exc)
+3 -3
View File
@@ -10,7 +10,7 @@ from collections.abc import Sequence
from pathlib import Path
import core_probe as cp
from core import upstream
from core import forgehttp
from core.statefile import now_iso
from probes.host import main_cache
from probes.standaloneemulators import Emulator
@@ -62,8 +62,8 @@ def fetch(emu: Emulator, cache: Path | None = None) -> dict:
folder = (cache or cache_root()) / emu.name
folder.mkdir(parents=True, exist_ok=True)
partial = folder / f"{asset['name']}.part"
# Whole or absent, retried on a cut stream (core.upstream.download).
upstream.download(asset["url"], partial, timeout=600)
# Whole or absent, retried on a cut stream (core.forgehttp.download).
forgehttp.download(asset["url"], partial, timeout=600)
sha256 = cp.file_digest(partial, "sha256")
target = folder / sha256 / asset["name"]
target.parent.mkdir(parents=True, exist_ok=True)
+2 -2
View File
@@ -10,7 +10,7 @@ import sys
from pathlib import Path
import core_probe as cp
from core import upstream
from core import forgehttp
from probes.appimage import fetch, github_releases, select_asset
from probes.standaloneemulators import EMULATORS, Emulator
from probes.standalonerecord import Busy, RunFailed, measure, validate
@@ -31,7 +31,7 @@ def run_mode(args: argparse.Namespace) -> int:
if args.mode == "fetch":
try:
print(json.dumps(fetch(emu), indent=2))
except (cp.ProbeError, upstream.UpstreamError, OSError, http.client.HTTPException,
except (cp.ProbeError, forgehttp.UpstreamError, OSError, http.client.HTTPException,
subprocess.CalledProcessError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
+1 -1
View File
@@ -7,7 +7,7 @@ import posixpath
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, replace
from core.upstream import CompareResult, find_renamed
from core.upstreamtree import CompareResult, find_renamed
from model.sourceref import RefPart, is_binary_citation
from profiling.citations import is_external_citation
from profiling.repos import HEAD, PIN
+6 -4
View File
@@ -10,7 +10,9 @@ import re
import sys
from core import upstream
from core.upstream import CompareResult
from core import forgehttp
from core import upstreamtree
from core.upstreamtree import CompareResult
from profiling.citations import collect_tokens
from profiling.reports import CitedSource, ProfileReport
@@ -284,9 +286,9 @@ def print_extras(
return
try:
_print_extras_from(args, report)
except upstream.RateLimitError:
except forgehttp.RateLimitError:
raise
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
print(f" extras skipped: {exc}")
@@ -310,7 +312,7 @@ def _print_extras_from(args: argparse.Namespace, report: ProfileReport) -> None:
by_repo.setdefault((source.repo.host, source.repo.slug), []).append(source)
for sources in by_repo.values():
first = sources[0]
comparison = upstream.compare(
comparison = upstreamtree.compare(
first.repo, first.pin, first.head, args.cache_dir, args.offline
)
if len(by_repo) > 1:
+2 -1
View File
@@ -12,6 +12,7 @@ from pathlib import Path
import yaml
from core import upstream
from core import upstreamtree
from model.sourceref import RefPart
from profiling.anchoring import anchor_block
from profiling.attribution import owner_order
@@ -153,7 +154,7 @@ def _resolve_at(
if lines is not None:
return "found", (candidate, lines)
if "/" not in path:
tree, truncated = upstream.list_tree(repo, sha, cache_dir, offline)
tree, truncated = upstreamtree.list_tree(repo, sha, cache_dir, offline)
matches = [p for p in tree or [] if posixpath.basename(p) == path]
if len(matches) == 1:
lines = upstream.fetch_file(
+2 -2
View File
@@ -6,7 +6,7 @@ import argparse
import sys
from pathlib import Path
from core import upstream
from core import forgehttp
from profiling.realign import realign_prose
from profiling.sourcepaths import record_write, refresh_source_paths
from profiling.yamledit import YamlWriteError
@@ -26,7 +26,7 @@ def run_realign(args: argparse.Namespace, selected: dict) -> None:
profile_path, args.cache_dir, args.offline, args.dry_run
):
print(f"{name}: {line}")
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
print(f"{name}: {exc}", file=sys.stderr)
failed.add(name)
except YamlWriteError as exc:
+11 -9
View File
@@ -7,6 +7,8 @@ from collections.abc import Iterable
from dataclasses import dataclass, replace
from core import upstream
from core import forgehttp
from core import upstreamtree
from model.profilerepos import declared_pin, declared_repositories, pin_field, serving_url
@@ -111,11 +113,11 @@ def select_views(
branch = declared if pinned_by == "source" else None
head = None
try:
unread: upstream.NotCachedError | None = None
unread: forgehttp.NotCachedError | None = None
for candidate in branch_candidates(url):
try:
head = upstream.resolve_head(repo, cache_dir, offline, candidate)
except upstream.NotCachedError as exc:
except forgehttp.NotCachedError as exc:
# Another prefix of the /tree/ tail may be the cached branch.
unread = exc
continue
@@ -130,7 +132,7 @@ def select_views(
if not pin or origin is None:
continue
head = head or upstream.resolve_head(repo, cache_dir, offline, branch)
except upstream.GoneError:
except forgehttp.GoneError:
# yuzu's source answers 451: the mirror declared after it is what
# keeps the profile checkable, so a gone repository is passed over.
gone = True
@@ -141,13 +143,13 @@ def select_views(
# A tip cached before the pin was written is older than the pin:
# scummvm-standalone pinned 6f7b060d while the cache still held
# 77d80d7, and a bump would have moved the pin backwards.
relation = upstream.ancestry(repo, pin, head, cache_dir, offline)
relation = upstreamtree.ancestry(repo, pin, head, cache_dir, offline)
if relation and relation[0] == 0 and relation[1] > 0:
head = upstream.resolve_head(repo, cache_dir, offline, branch, fresh=True) or head
seen.add((repo.host, repo.slug))
views.append(RepoView(repo, pin, head, origin, field_name, mode))
if gone and not views:
raise upstream.GoneError(f"{profile.get('emulator', '?')}: every declared repository is gone")
raise forgehttp.GoneError(f"{profile.get('emulator', '?')}: every declared repository is gone")
views = _follow_fork_base(_follow_submodule(views, cache_dir, offline), cache_dir, offline)
return _hold_upstream(profile, views)
@@ -184,7 +186,7 @@ def _follow_submodule(
return views
pinned = {
sha: path
for path, sha in upstream.list_gitlinks(
for path, sha in upstreamtree.list_gitlinks(
source.repo, source.pin, cache_dir, offline
).items()
}
@@ -194,7 +196,7 @@ def _follow_submodule(
for view in views:
path = pinned.get(view.pin) if view.field == "upstream" else None
head = (
upstream.list_gitlinks(source.repo, source.head, cache_dir, offline).get(path)
upstreamtree.list_gitlinks(source.repo, source.head, cache_dir, offline).get(path)
if path else None
)
followed.append(
@@ -222,7 +224,7 @@ def _follow_fork_base(
if view.field != "upstream" or view.pin == view.head or " via " in view.origin:
followed.append(view)
continue
base = upstream.fork_base(
base = upstreamtree.fork_base(
view.repo, view.head, source.repo, source.head, cache_dir, offline
)
if base and base != view.pin:
@@ -230,7 +232,7 @@ def _follow_fork_base(
# carry: the upstream is a build of its own, the Qt melonDS or the
# EasyRPG Player a standalone + libretro profile documents, and
# its HEAD stays the reference. melonds read 825 commits back.
moved = upstream.ancestry(view.repo, base, view.pin, cache_dir, offline)
moved = upstreamtree.ancestry(view.repo, base, view.pin, cache_dir, offline)
if moved and moved[0] > 0 and moved[1] == 0:
base = None
followed.append(
+15 -13
View File
@@ -11,7 +11,9 @@ from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field, replace
from core import upstream
from core.upstream import CompareResult
from core import forgehttp
from core import upstreamtree
from core.upstreamtree import CompareResult
from model.sourceref import RefPart, ref_role, resolve_project_word, split_source_ref
from profiling.anchoring import (
BLANK_LOOKAHEAD,
@@ -246,9 +248,9 @@ def _readable_views(
try:
views = select_views(profile, cache_dir, offline)
except upstream.RateLimitError:
except forgehttp.RateLimitError:
raise
except upstream.UpstreamError:
except forgehttp.UpstreamError:
# citron's dead domain now resolves to an unrelated host that fails
# TLS: for a forge the profile declares gone, any refusal agrees.
if stated_gone:
@@ -319,7 +321,7 @@ def _record_revisions(
f"{view.repo.slug}: pin {view.pin[:8]} is no ancestor of {view.head[:8]}"
for view in views
if not reads_own_revision(view, tagged)
and upstream.compare(
and upstreamtree.compare(
view.repo, view.pin, view.head, cache_dir, offline
).diverged
]
@@ -416,8 +418,8 @@ class _Resolver:
known: the parts it cannot place stay external, as before."""
for view in self.views:
try:
yield upstream.list_gitlinks(view.repo, view.pin, self.cache_dir, self.offline)
except upstream.TruncatedListingError as exc:
yield upstreamtree.list_gitlinks(view.repo, view.pin, self.cache_dir, self.offline)
except forgehttp.TruncatedListingError as exc:
print(f"{self.name}: submodule paths unknown, {exc}", file=sys.stderr)
yield ()
@@ -588,7 +590,7 @@ class _Resolver:
"""Tree at the revision the refs were written against, memoised."""
key = view.repo.slug
if key not in self.pin_trees:
tree, _ = upstream.list_tree(view.repo, view.pin, self.cache_dir, self.offline)
tree, _ = upstreamtree.list_tree(view.repo, view.pin, self.cache_dir, self.offline)
self.pin_trees[key] = tree
return self.pin_trees[key]
@@ -614,10 +616,10 @@ class _Resolver:
# A file of a submodule is read at the commit its gitlink
# pins in this revision, so a bump moves it with the port.
try:
inner = upstream.through_gitlink(
inner = upstreamtree.through_gitlink(
repo, sha, wanted, self.cache_dir, self.offline
)
except upstream.TruncatedListingError as exc:
except forgehttp.TruncatedListingError as exc:
# The tree is listed in part: the path may sit in a
# submodule nobody can see, which is no reason to mute
# every other file of the repository.
@@ -627,9 +629,9 @@ class _Resolver:
if inner is not None:
found = upstream.fetch_file(*inner, self.cache_dir, self.offline)
return found
except (upstream.RateLimitError, upstream.NotCachedError):
except (forgehttp.RateLimitError, forgehttp.NotCachedError):
raise
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
self.mute.add(key)
print(f"{self.name}: {repo.host}/{repo.slug} muted, {exc}", file=sys.stderr)
return None
@@ -637,10 +639,10 @@ class _Resolver:
def context_for(self, view: RepoView) -> tuple[CompareResult, list[str]]:
key = view.repo.slug
if key not in self.context:
comparison = upstream.compare(
comparison = upstreamtree.compare(
view.repo, view.pin, view.head, self.cache_dir, self.offline
)
tree, truncated = upstream.list_tree(
tree, truncated = upstreamtree.list_tree(
view.repo, view.head, self.cache_dir, self.offline
)
self.context[key] = (comparison, tree)
+18 -16
View File
@@ -12,6 +12,8 @@ from pathlib import Path
import yaml
from core import upstream
from core import forgehttp
from core import upstreamtree
from profiling.bump import bump_commit, pins_changed
from profiling.detection import detect_upstream_changes, print_extras
from profiling.realign import realign_prose
@@ -76,12 +78,12 @@ def _read_stale_prose(
"""
try:
return realign_prose(path, args.cache_dir, args.offline, dry_run=True)
except upstream.RateLimitError:
except forgehttp.RateLimitError:
raise
except upstream.NotCachedError as exc:
except forgehttp.NotCachedError as exc:
# Unread offline, as a report is: not clean, and not a failure.
return [f"not read offline: {exc}"]
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
# Not read is not clean: the bump would refuse on the same error.
print(f"{name}: prose not read, {exc}", file=sys.stderr)
failed.add(name)
@@ -269,9 +271,9 @@ def _attach_detection(
return
try:
detect_upstream_changes(profile, report, cache_dir, offline, files, hashes)
except upstream.RateLimitError:
except forgehttp.RateLimitError:
raise
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
report.detection_skipped = str(exc)
@@ -303,16 +305,16 @@ def _version_of(
passed = None
try:
if version and version.tag_commit and pin and version.tag_commit != pin:
relation = upstream.ancestry(
relation = upstreamtree.ancestry(
repo, version.tag_commit, pin, args.cache_dir, args.offline
)
passed = latest_passed_release(repo, version, pin, args.cache_dir, args.offline)
newer = None if passed or profile.get(frozen_by) else newer_release(
repo, version, pin, args.cache_dir, args.offline
)
except upstream.RateLimitError:
except forgehttp.RateLimitError:
raise
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
report.version_unread = f"tag ancestry unread: {exc}"
newer = None
warning = version_warning(version, pin, relation, passed) or (
@@ -340,9 +342,9 @@ def _attach_version(
for named in named_tags:
try:
version, warning = _version_of(args, profile, report, named)
except upstream.RateLimitError:
except forgehttp.RateLimitError:
raise
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
report.version_unread = f"version check skipped: {exc}"
return
if report.version is None:
@@ -368,7 +370,7 @@ def read_one_profile(
profile_path = Path(args.emulators_dir) / f"{name}.yml"
try:
report = _build_full_report(args, name, profile, profile_path, failed)
except upstream.RateLimitError as exc:
except forgehttp.RateLimitError as exc:
# A quota is one forge's: git.libretro.com answering 429 said
# nothing about the 600 profiles on GitHub. upstream stops asking
# that host, so the rest of the pass costs it nothing.
@@ -386,7 +388,7 @@ def read_one_profile(
# The guard already left the file untouched, so keep going.
print(f"{name}: write refused: {exc}", file=sys.stderr)
failed.add(name)
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
# A prose read the writes need could not be made (offline with
# a cold cache, a forge down): the profile was put back, and one
# profile must not end the pass for the others.
@@ -450,20 +452,20 @@ def _build_full_report(
profile_path.read_text(encoding="utf-8")
if profile_path.is_file() else None,
)
except upstream.RateLimitError:
except forgehttp.RateLimitError:
raise
except upstream.NotCachedError as exc:
except forgehttp.NotCachedError as exc:
# Offline with a cache that never stored this file: the profile
# is unverified, not wrong. Reporting GONE sent readers after
# files that exist.
report = _skipped(name, SkipKind.OFFLINE, f"offline: {exc}")
except upstream.GoneError as exc:
except forgehttp.GoneError as exc:
# The forge is not coming back: a takedown, or a host that no
# longer resolves. Saying so once in the summary beats repeating
# it on stderr every pass, and it keeps the profile out of the
# backlog, where nobody can act on it anyway.
report = _skipped(name, SkipKind.GONE, f"upstream gone: {exc}")
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
# One unreachable forge must not abandon the other profiles.
print(f"{name}: {exc}", file=sys.stderr)
report = _skipped(name, SkipKind.UPSTREAM_ERROR, f"upstream error: {exc}")
+2 -1
View File
@@ -9,6 +9,7 @@ from collections.abc import Sequence
from dataclasses import dataclass, field
from core import upstream
from core import forgehttp
from profiling.reports import ProfileReport, report_to_dict, triage_state
from profiling.versionbasis import version_repo, version_tags
from profiling.versions import VersionReport, check_version
@@ -173,7 +174,7 @@ def _score(
source.repo, source.path, source.pin, args.cache_dir, args.offline,
head=source.head,
)
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
# One forge refusing a request (Eden's answers 403 to commit
# lookups) leaves this profile unscored, not the whole ranking.
refused = "commit history unreachable"
+10 -8
View File
@@ -33,6 +33,8 @@ from collections.abc import Callable
from dataclasses import dataclass
from core import upstream
from core import forgehttp
from core import upstreamtree
from model.profilerepos import pin_field
from profiling.repos import resolve_pin, select_repo
@@ -224,15 +226,15 @@ def _ancestry(
"""The forge's compare, else the commit graph: GitHub refuses with 422
a compare whose diff is too large (aps3e's tag and pin)."""
try:
relation = upstream.ancestry(repo, base, head, cache_dir, offline)
except upstream.RateLimitError:
relation = upstreamtree.ancestry(repo, base, head, cache_dir, offline)
except forgehttp.RateLimitError:
raise
except upstream.UpstreamError:
except forgehttp.UpstreamError:
relation = None
if relation is None:
try:
relation = upstream.graph_ancestry(repo, base, head, cache_dir, offline)
except upstream.NotCachedError:
relation = upstreamtree.graph_ancestry(repo, base, head, cache_dir, offline)
except forgehttp.NotCachedError:
return None
return relation
@@ -267,7 +269,7 @@ def _read_none(req: _Request) -> Reading:
# 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)
described = upstreamtree.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),
@@ -317,7 +319,7 @@ def _read_file(req: _Request, repo: upstream.Repo, pin: str) -> Reading:
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"))
described = upstreamtree.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
@@ -375,7 +377,7 @@ def read(
on_forge = _ON_FORGE.get(kind)
if on_forge is not None:
return on_forge(req, repo, pin)
except (upstream.UpstreamError, VersionUnreadable) as exc:
except (forgehttp.UpstreamError, VersionUnreadable) as exc:
return req.unreadable(str(exc))
return req.unreadable(f"unknown kind {kind!r}")
+8 -6
View File
@@ -6,6 +6,8 @@ import re
from dataclasses import dataclass
from core import upstream
from core import forgehttp
from core import upstreamtree
from profiling.versionbasis import VersionTag, declared
@@ -68,9 +70,9 @@ def page_version(
return None, "version_source names no url or pattern"
try:
text = upstream.fetch_page(url, cache_dir, offline)
except upstream.NotCachedError:
except forgehttp.NotCachedError:
return None, "not cached offline"
except upstream.UpstreamError as exc:
except forgehttp.UpstreamError as exc:
return None, f"{url}: {exc}"
if text is None:
return None, "page absent"
@@ -206,10 +208,10 @@ def newer_release(
commit = upstream.tag_commit(repo, published, cache_dir, offline)
if not commit or commit == pin:
return None
after_tag = upstream.ancestry(repo, version.tag_commit, commit, cache_dir, offline)
after_tag = upstreamtree.ancestry(repo, version.tag_commit, commit, cache_dir, offline)
if not after_tag or after_tag[0] == 0 or after_tag[1] != 0:
return None
after_pin = upstream.ancestry(repo, pin, commit, cache_dir, offline)
after_pin = upstreamtree.ancestry(repo, pin, commit, cache_dir, offline)
if not after_pin or after_pin[0] == 0:
return None
return published
@@ -245,12 +247,12 @@ def latest_passed_release(
if version.tag_commit and version.tag_commit != commit:
# A project can publish a release older than its newest tag:
# pcsx2x6's latest release is v0.2.20, its declared tag v0.2.22.
older = upstream.ancestry(repo, commit, version.tag_commit, cache_dir, offline)
older = upstreamtree.ancestry(repo, commit, version.tag_commit, cache_dir, offline)
if older and older[1] == 0:
return None
if commit == pin:
return published
relation = upstream.ancestry(repo, commit, pin, cache_dir, offline)
relation = upstreamtree.ancestry(repo, commit, pin, cache_dir, offline)
if relation and relation[1] == 0:
return published
return None
+1 -1
View File
@@ -7,7 +7,7 @@ import urllib.error
import urllib.parse
import urllib.request
from core.upstream import forge_headers, open_retrying
from core.forgehttp import forge_headers, open_retrying
from release.downloaderror import DownloadError
DEFAULT_API = "https://api.github.com"
+1 -1
View File
@@ -9,7 +9,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Protocol
from core.hashing import compute_hashes, parse_sha256sums
from core.upstream import open_retrying
from core.forgehttp import open_retrying
from release.downloaderror import DownloadError
from release.latest import checked_url
from release.transfer import TRANSFER_ERRORS, download_file
+2 -2
View File
@@ -7,7 +7,7 @@ import urllib.error
import urllib.request
from typing import TYPE_CHECKING
from core.upstream import UpstreamError, open_retrying
from core.forgehttp import UpstreamError, open_retrying
from release.downloaderror import DownloadError
from release.latest import checked_url
@@ -27,7 +27,7 @@ def download_file(
"""Write the asset at *url* to *dest* and return its byte count.
*progress* receives the bytes written so far and the announced total
after each block. core.upstream.open_retrying asks again after a dropped
after each block. core.forgehttp.open_retrying asks again after a dropped
connection, a stream cut midway or a 5xx, and waits out a rate limit:
each attempt writes `dest` from its first byte. A transfer that fails or
ends short of *expected_size* raises DownloadError.
+4 -3
View File
@@ -16,6 +16,7 @@ from enum import Enum
from pathlib import Path
from core import upstream
from core import forgehttp
from model.database import record_at, record_for_hash, sha1_at
from model.largefiles import asset_candidates, asset_names, fetch_large_file
from core.hashing import declared_hash_lists, file_digest
@@ -97,7 +98,7 @@ def download_external(
"""Download a `storage: external` file, verify its hash, write dest_path.
The run's network policy applies: under --offline nothing is fetched and
the entry stays missing, as verify reports it. core.upstream.download
the entry stays missing, as verify reports it. core.forgehttp.download
streams the body to a scratch beside dest_path, retried on a transient
failure, and dest_path is written only once the scratch hashes to the
declared value. Nothing is printed: the caller reports the outcome.
@@ -115,12 +116,12 @@ def download_external(
algo, expected = declared[0], set(declared[1])
Path(dest_path).parent.mkdir(parents=True, exist_ok=True)
try:
served = upstream.download(
served = forgehttp.download(
url, dest_path, timeout=120, user_agent="retrobios-pack-gen/1.0",
accept=lambda scratch: file_digest(Path(scratch), algo) in expected,
)
except (urllib.error.URLError, OSError, http.client.HTTPException,
upstream.UpstreamError, ValueError) as exc:
forgehttp.UpstreamError, ValueError) as exc:
return ExternalFetch(ExternalOutcome.NETWORK_ERROR, f"{url}: {exc}")
if served is None:
return ExternalFetch(ExternalOutcome.MISMATCH, algo.upper())
+7 -8
View File
@@ -20,17 +20,16 @@ from typing import Any, Callable, Iterator, NoReturn, TypeVar
from core.github import github_token
from core.artifacts import write_text_atomic
from core.hashing import git_blob_sha
from core.upstream import (
from core.forgehttp import (
MAX_RESPONSE_SIZE,
RateLimitError,
UpstreamError,
make_repo,
open_retrying,
read_limited,
resolve_head,
)
from core.upstream import download as upstream_download
from core.upstream import forge_headers as upstream_headers
from core.upstream import make_repo, resolve_head
from core.forgehttp import download as upstream_download
from core.forgehttp import forge_headers as upstream_headers
from model.safeparse import require_yaml
from model.sources import source_yaml_file
@@ -173,7 +172,7 @@ class FetchError(ConnectionError):
def forge_headers(url: str, accept: str | None = None) -> dict[str, str]:
"""Request headers for `url`: the GitHub token goes to GitHub's API and
raw hosts only, compared whole (core.upstream.forge_headers)."""
raw hosts only, compared whole (core.forgehttp.forge_headers)."""
return upstream_headers(url, accept, SCRAPER_AGENT)
@@ -207,7 +206,7 @@ def _open(
timeout: float,
) -> _T:
"""Open `request` and hand the response to `consume`, retried as
core.upstream.open_retrying does. A header the request does not set
core.forgehttp.open_retrying does. A header the request does not set
comes from forge_headers(). A failure raises FetchError."""
url = request.full_url
for name, value in forge_headers(url).items():
@@ -264,7 +263,7 @@ def download(
"""Stream `url` into `destination`, whole or not at all, and return the
response's Content-Disposition ("" when absent or when skipped).
core.upstream.download does the work: a scratch file renamed into place,
core.forgehttp.download does the work: a scratch file renamed into place,
so a reader or an interrupted run never sees half an archive.
`skip_existing` keeps a file already there without asking the server.
A failure raises FetchError.
+1 -1
View File
@@ -6,7 +6,7 @@ import logging
import urllib.error
import urllib.parse
from core.upstream import remote_etag as get_remote_etag
from core.forgehttp import remote_etag as get_remote_etag
from core.paths import DATA_DIRS_FILE
from model.registry import data_dir_registry_at, load_versions, versions_file_for
from .base_scraper import fetch_text
+2 -1
View File
@@ -29,6 +29,7 @@ from model.sources import source_yaml_file
from core.cli import SourceUnreadable
from core import upstream
from core import upstreamtree
from .base_scraper import fetch_github_latest_version
from ._hash_merge import (
@@ -473,7 +474,7 @@ def _merge_devices(args: argparse.Namespace) -> None:
device["systems"] = filed.get(set_name, [])
report = merge_mame_devices(str(profile_path), devices, write=not args.dry_run)
shipped = upstream.list_directory(repo, commit, "hash", upstream.CACHE_DIR)
shipped = upstreamtree.list_directory(repo, commit, "hash", upstream.CACHE_DIR)
if shipped is None:
raise RuntimeError(f"hash/ of {repo.slug} at {commit} could not be listed")
present = {name[:-4] for name in shipped if name.endswith(".xml")}
+4 -4
View File
@@ -17,7 +17,7 @@ from __future__ import annotations
from collections.abc import Container
from core import upstream
from core import upstreamtree
from model.safeparse import parse_untrusted_xml
from .base_scraper import BaseScraper, BiosRequirement, fetch_bytes, systems_from_requirements
@@ -122,13 +122,13 @@ def tree_listing(directory: str, tag: str) -> list[dict]:
import json
entries: list[dict] = []
for page in range(1, upstream.MAX_TREE_PAGES + 1):
for page in range(1, upstreamtree.MAX_TREE_PAGES + 1):
url = TREE_URL.format(
path=directory, tag=tag, per_page=upstream.TREE_PAGE_SIZE, page=page
path=directory, tag=tag, per_page=upstreamtree.TREE_PAGE_SIZE, page=page
)
listing = json.loads(fetch_bytes(url))
entries += [item for item in listing if isinstance(item, dict)]
if len(listing) < upstream.TREE_PAGE_SIZE:
if len(listing) < upstreamtree.TREE_PAGE_SIZE:
return entries
raise RuntimeError(f"{directory} at {tag} outruns the page cap")
# One raw read per system.ini made about 150 requests and GitLab throttled
+4 -3
View File
@@ -26,6 +26,7 @@ if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[2])) not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
from core import upstream
from core import upstreamtree
from ..base_scraper import PlatformDumper
@@ -85,7 +86,7 @@ class Fetcher:
repo, sha = self._repo(key)
if repo.family == "gitlab" and prefix.strip("/"):
return self._gitlab_subtree(repo, sha, prefix)
paths, truncated = upstream.list_tree(repo, sha, self.cache_dir, self.offline)
paths, truncated = upstreamtree.list_tree(repo, sha, self.cache_dir, self.offline)
if truncated:
raise SourceError(f"{repo.slug}@{sha[:8]}: the forge truncated the tree")
return sorted(p for p in paths if p.startswith(prefix))
@@ -94,7 +95,7 @@ class Fetcher:
"""Fetch a whole GitLab directory in one archive request before its
files are read one by one. A no-op on other forges."""
repo, sha = self._repo(key)
held = upstream.cache_gitlab_directory(repo, sha, directory, self.cache_dir, self.offline)
held = upstreamtree.cache_gitlab_directory(repo, sha, directory, self.cache_dir, self.offline)
if held is not None:
self._cached_dirs.setdefault(key, {})[directory.strip("/")] = held
@@ -120,7 +121,7 @@ class Fetcher:
self, repo: upstream.Repo, sha: str, directory: str, *, recursive: bool, blobs: bool
) -> list[str]:
directory = directory.strip("/")
entries, truncated = upstream.gitlab_tree_entries(
entries, truncated = upstreamtree.gitlab_tree_entries(
repo, sha, self.cache_dir, self.offline, path=directory, recursive=recursive
)
if truncated:
+1 -1
View File
@@ -12,7 +12,7 @@ import sys
from pathlib import Path
from . import Fetcher, SourceError, dump_setup, scrape_setup
from core.upstream import UpstreamError
from core.forgehttp import UpstreamError
from core.artifacts import write_if_changed
from model.romfolders import ROMFOLDERS_DIR, SOURCES_DIR, load_sources
+2 -2
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
from core import upstream
from core import forgehttp
from sitegen.agents import INDEXNOW_FILE, INDEXNOW_KEY, PUBLISHER, SITE
HOST = PUBLISHER
@@ -16,7 +16,7 @@ USER_AGENT = "retrobios-indexnow"
def live_digests(url: str = f"{SITE}digests.json") -> dict[str, str]:
"""The digests the live site serves. None yet (the first deploy that
writes them) is an empty map: every page is new."""
body = upstream.fetch_body(url, timeout=60, user_agent=USER_AGENT)
body = forgehttp.fetch_body(url, timeout=60, user_agent=USER_AGENT)
return {} if body is None else json.loads(body.decode("utf-8"))
+7 -7
View File
@@ -19,7 +19,7 @@ from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from core import upstream
from core import forgehttp
from core.artifacts import write_text_atomic
from core.cli import SourceUnreadable
from core.github import github_token
@@ -37,7 +37,7 @@ USER_AGENT = "retrobios-site-insights"
EXPORT_POLL = 5
EXPORT_TRIES = 60
# GoatCounter answers four requests a second and 500 per window, and says
# when to come back in X-Rate-Limit-Reset. core.upstream.open_retrying waits
# when to come back in X-Rate-Limit-Reset. core.forgehttp.open_retrying waits
# a short wait and gives up on a long one, which ends the run.
# Expected click-through rate: the site's own rate at each rounded
@@ -83,15 +83,15 @@ class SourceUnavailable(Exception):
def _open(request: urllib.request.Request) -> tuple[int, bytes]:
"""Status and body of a request, retried by core.upstream.open_retrying:
"""Status and body of a request, retried by core.forgehttp.open_retrying:
a dropped connection or a 5xx is asked again, a rate limit waited out."""
try:
return upstream.open_retrying(request, lambda response: (response.status, response.read()), 60)
except (urllib.error.HTTPError, upstream.RateLimitError) as error:
return forgehttp.open_retrying(request, lambda response: (response.status, response.read()), 60)
except (urllib.error.HTTPError, forgehttp.RateLimitError) as error:
if isinstance(error, urllib.error.HTTPError) and error.code != 429:
raise
headers = error.headers if isinstance(error, urllib.error.HTTPError) else None
wait = upstream.requested_wait(headers)
wait = forgehttp.requested_wait(headers)
delay = f" for {wait:.0f} s" if wait is not None else ""
raise SourceUnavailable(f"{urllib.parse.urlsplit(request.full_url).hostname} refuses requests"
f"{delay} (rate limit); run again then", wait) from error
@@ -220,7 +220,7 @@ def fetch_github() -> dict:
if not github_token():
raise SourceUnavailable("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login")
api = f"https://api.github.com/repos/{REPOSITORY}"
auth = upstream.forge_headers(api, "application/vnd.github+json", USER_AGENT)
auth = forgehttp.forge_headers(api, "application/vnd.github+json", USER_AGENT)
releases = _get_json(f"{api}/releases?per_page=10", auth)
return {
"views": _get_json(f"{api}/traffic/views", auth),
+3 -2
View File
@@ -18,6 +18,7 @@ from core.artifacts import write_if_changed
from core.paths import DB_FILE, REPO_ROOT
from core.sizes import size_text
from core import upstream
from core import forgehttp
from installer_build.module import installer_module
from model.guides import PACKAGE_COMMAND
from sitegen.guidedata import install_command
@@ -161,9 +162,9 @@ def fetch_contributors() -> list[dict]:
return []
url = f"https://api.github.com/repos/{REPO}/contributors"
try:
body = upstream.fetch_body(url, accept_json=True, timeout=10, user_agent="retrobios-readme/1.0")
body = forgehttp.fetch_body(url, accept_json=True, timeout=10, user_agent="retrobios-readme/1.0")
data = json.loads(body) if body is not None else []
except (upstream.UpstreamError, ValueError) as exc:
except (forgehttp.UpstreamError, ValueError) as exc:
print(f"contributors: {exc}", file=sys.stderr)
return []
owner = REPO.split("/")[0]
+6 -4
View File
@@ -12,6 +12,8 @@ from pathlib import Path
from core.text import series
from core import upstream
from core import forgehttp
from core import upstreamtree
from core.artifacts import repository_output_lock, write_if_changed
from core.paths import REPO_ROOT
from model.citations import document_citations, known_repositories
@@ -217,8 +219,8 @@ def _cached_tree(
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
paths, truncated = upstream.list_tree(repo, pin, str(cache_dir), offline=not online)
except upstream.UpstreamError as exc:
paths, truncated = upstreamtree.list_tree(repo, pin, str(cache_dir), offline=not online)
except forgehttp.UpstreamError as exc:
print(f" {tree_key(repo, pin)}: {exc}", file=sys.stderr)
return None
if paths and not truncated:
@@ -277,8 +279,8 @@ def _listed_directories(
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
names = upstream.list_directory(repo, pin, folder, str(cache_dir), offline=not online)
except upstream.UpstreamError:
names = upstreamtree.list_directory(repo, pin, folder, str(cache_dir), offline=not online)
except forgehttp.UpstreamError:
names = None
if names is not None:
break
+8 -8
View File
@@ -3543,7 +3543,7 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
from sitegen import readme
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \
mock.patch.object(readme.upstream, "fetch_body",
mock.patch.object(readme.forgehttp, "fetch_body",
side_effect=AssertionError("network")):
self.assertEqual(readme.fetch_contributors(), [])
@@ -3556,7 +3556,7 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
{"login": readme.REPO.split("/")[0], "type": "User"},
]).encode()
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(readme.upstream, "fetch_body", return_value=answer) as fetch:
mock.patch.object(readme.forgehttp, "fetch_body", return_value=answer) as fetch:
self.assertEqual([c["login"] for c in readme.fetch_contributors()], ["someone"])
self.assertIn("/contributors", fetch.call_args.args[0])
@@ -4502,7 +4502,7 @@ class TriageSurvivesAForgeRefusal(unittest.TestCase):
def check_version(named, *_args):
if "eden" in named.repo.slug:
raise triage.upstream.UpstreamError("HTTP 403")
raise triage.forgehttp.UpstreamError("HTTP 403")
return
args = SimpleNamespace(cache_dir="", offline=True)
@@ -7015,7 +7015,7 @@ class AnUnansweredSearchIsNotANotFound(unittest.TestCase):
entry = {"name": "nowhere.bin", "system": "test-system", "sha1": "0" * 40}
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}}}
with mock.patch("urllib.request.urlopen", refuse), \
mock.patch.object(acquire_fetch.upstream, "_sleep", lambda _s: None), \
mock.patch.object(acquire_fetch.forgehttp, "_sleep", lambda _s: None), \
mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None):
return acquire_fetch.fetch_missing([entry], db, "bios")
@@ -7857,7 +7857,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
def test_each_failure_names_its_own_cause(self):
"""Four causes came back as one False, reported as a download failure."""
from core import upstream
from core import forgehttp
from resolve import packfiles as packresolve
outcome = packresolve.ExternalOutcome
@@ -7868,7 +7868,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
offline = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True)
with mock.patch("urllib.request.urlopen",
side_effect=urllib.error.URLError("refused")), \
mock.patch.object(upstream, "_sleep", lambda _s: None):
mock.patch.object(forgehttp, "_sleep", lambda _s: None):
failed = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False)
self.assertIs(no_hash.outcome, outcome.NO_HASH)
self.assertIs(offline.outcome, outcome.OFFLINE)
@@ -7934,7 +7934,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
def test_a_transient_failure_is_retried_and_no_scratch_remains(self):
"""One 503 failed the external file for the whole build."""
from core import upstream
from core import forgehttp
from resolve import packfiles as packresolve
refusal = urllib.error.HTTPError(self.ENTRY["source_url"], 503, "busy", {}, None)
@@ -7942,7 +7942,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
target = Path(tmp) / "x"
with mock.patch("urllib.request.urlopen",
side_effect=[refusal, self._response(b"payload")]), \
mock.patch.object(upstream, "_sleep", lambda _s: None):
mock.patch.object(forgehttp, "_sleep", lambda _s: None):
self.assertTrue(
packresolve.download_external(self.ENTRY, str(target), offline=False).fetched)
self.assertEqual(target.read_bytes(), b"payload")
+16 -16
View File
@@ -48,20 +48,20 @@ def _serving(payloads: dict[str, bytes]):
class SoftwareHeritageAnswersByContent(unittest.TestCase):
def test_the_bytes_it_serves_are_kept_when_the_hash_holds(self):
urlopen, asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1}, [])
self.assertEqual(data, PAYLOAD)
self.assertEqual(asked, [f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"])
def test_other_bytes_under_the_hash_are_refused(self):
urlopen, _asked = _serving({fetch.SOFTWARE_HERITAGE: b"something else"})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}, [])
self.assertIsNone(data)
def test_an_absent_file_is_not_counted_as_a_source_that_did_not_answer(self):
urlopen, _asked = _serving({})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
found = fetch.search({"name": "x", "sha1": SHA1}, fetch.SHA1_SOURCES)
self.assertEqual(found, fetch.SearchResult(None, None, ()))
@@ -76,7 +76,7 @@ class LookupBySha1(unittest.TestCase):
def test_a_found_file_goes_to_tmp_acquire_never_to_bios(self):
urlopen, _asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
[record] = fetch.lookup_sha1s([SHA1.upper()], {"files": {}},
acquire_dir=self.acquire)
self.assertEqual((record.outcome, record.source), ("found", "software_heritage"))
@@ -92,7 +92,7 @@ class LookupBySha1(unittest.TestCase):
def test_a_held_file_is_named_and_not_fetched(self):
urlopen, asked = _serving({})
db = {"files": {SHA1: {"path": "bios/Commodore/Amiga/x.rom"}}}
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen), \
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen), \
contextlib.redirect_stdout(io.StringIO()) as out:
code = fetchtext.report_lookups([SHA1], db, acquire_dir=self.acquire)
self.assertEqual((code, asked), (0, []))
@@ -100,7 +100,7 @@ class LookupBySha1(unittest.TestCase):
def test_nothing_found_and_a_malformed_hash_end_with_one(self):
urlopen, _asked = _serving({})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen), \
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
code = fetchtext.report_lookups([SHA1, "not-a-hash"], {"files": {}},
@@ -139,13 +139,13 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
A 429 from Software Heritage was recorded unanswered at once."""
def setUp(self):
from core import upstream
from core import forgehttp
patcher = mock.patch.object(upstream, "_sleep", lambda _s: None)
patcher = mock.patch.object(forgehttp, "_sleep", lambda _s: None)
patcher.start()
self.addCleanup(patcher.stop)
upstream._exhausted_hosts.clear()
self.addCleanup(upstream._exhausted_hosts.clear)
forgehttp._exhausted_hosts.clear()
self.addCleanup(forgehttp._exhausted_hosts.clear)
def test_a_stalled_read_is_recorded_and_the_search_goes_on(self):
class _Stalled(_Answer):
@@ -156,7 +156,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
return _Stalled()
unanswered: list[str] = []
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
self.assertIsNone(fetch.step3_search_public_repos(
{"name": "x.bin", "sha1": SHA1}, unanswered))
self.assertEqual(len(unanswered), len(fetch.PUBLIC_REPOS))
@@ -170,7 +170,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
raise answer
return _Answer(answer)
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
found = fetch.search({"name": "x", "sha1": SHA1}, fetch.SHA1_SOURCES)
self.assertEqual(found, fetch.SearchResult(PAYLOAD, "software_heritage", ()))
@@ -184,7 +184,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
return _Answer(b"0" * 64)
with mock.patch.object(fetch, "MAX_DOWNLOAD", 32), \
mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step3_search_public_repos(
{"name": "x.bin", "destination": "sub/x.bin", "sha1": SHA1}, [])
self.assertEqual(data, PAYLOAD)
@@ -212,7 +212,7 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
def test_the_member_is_found_by_its_sha1_whatever_its_name(self):
urlopen, asked = self._archive()
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step4_search_archive_org(
{"name": "scph1001.bin", "sha1": SHA1.upper()}, [])
self.assertEqual(data, PAYLOAD)
@@ -220,7 +220,7 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
def test_the_platform_search_and_the_sha1_search_agree(self):
urlopen, _asked = self._archive()
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
by_platform = fetch.step4_search_archive_org(
{"name": "scph1001.bin", "sha1": SHA1}, [])
by_sha1 = fetch.archive_org_by_sha1(SHA1, [])
@@ -228,7 +228,7 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
def test_a_declared_md5_still_has_to_hold(self):
urlopen, _asked = self._archive()
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step4_search_archive_org(
{"name": "scph1001.bin", "sha1": SHA1, "md5": "f" * 32}, [])
self.assertIsNone(data)
+4 -2
View File
@@ -20,6 +20,8 @@ from unittest import mock
from pathlib import Path
from core import upstream
from core import forgehttp
from core import upstreamtree
from core.cli import InputMissing
from exporter.native import ExportResult
from exporter.originals import SOURCES_INDEX
@@ -468,7 +470,7 @@ class SiteNpmPins(unittest.TestCase):
name = url.split("registry.npmjs.org/", 1)[1].rsplit("/latest", 1)[0]
return {"version": latest[name]}
with mock.patch("freshness.ci.SITE_PACKAGE", package), \
mock.patch.object(upstream, "http_json", side_effect=answer):
mock.patch.object(forgehttp, "http_json", side_effect=answer):
rows = {f.subject: f for f in _npm_findings()}
self.assertEqual(rows["npm:astro"].status, STALE)
self.assertEqual(rows["npm:astro"].remote, "7.4.7")
@@ -546,7 +548,7 @@ class RomFolderPins(unittest.TestCase):
with mock.patch.object(upstream, "commit_date", return_value="2026-10-01T00:00:00"), \
mock.patch.object(upstream, "latest_release", return_value=None), \
mock.patch.object(upstream, "resolve_head", side_effect=lambda repo, _c: heads.get(repo.slug)), \
mock.patch.object(upstream, "ancestry", return_value=(5, 0)):
mock.patch.object(upstreamtree, "ancestry", return_value=(5, 0)):
rows = {f.subject: f for f in check_romfolders(root, "", False)}
self.assertEqual(rows["card"].status, OK)
self.assertEqual((rows["card:dist"].status, rows["card:dist"].detail),
+2 -1
View File
@@ -14,6 +14,7 @@ import unittest
from pathlib import Path
from core import upstream
from core import forgehttp
from model.safeparse import yaml_load
ROOT = Path(__file__).resolve().parents[1]
@@ -47,7 +48,7 @@ class CitedLinesHoldTheirCode(unittest.TestCase):
lines = upstream.fetch_file(
repo, str(document["source_commit"]), path, str(CACHE), True
)
except upstream.NotCachedError:
except forgehttp.NotCachedError:
self.skipTest(f"{path} is not in the upstream cache")
self.assertIsNotNone(lines)
self.assertIn(text, lines[line - 1])
+4 -4
View File
@@ -886,7 +886,7 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
"""One reset midway through a 2 GiB part failed the whole download."""
import http.client
from core import upstream
from core import forgehttp
class Body(io.BytesIO):
headers = {"Content-Length": "6"}
@@ -905,7 +905,7 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory, \
mock.patch.object(transfer.urllib.request, "urlopen",
lambda *a, **k: answers.pop(0)), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
mock.patch.object(forgehttp, "_sleep", lambda _s: None), \
contextlib.redirect_stdout(io.StringIO()):
target = Path(directory) / "a.zip"
transfer.download_file("https://example.com/a.zip", target, 6)
@@ -942,14 +942,14 @@ class ATransferFailureIsADownloadError(unittest.TestCase):
)
def test_a_transport_failure_raises(self):
from core import upstream
from core import forgehttp
def refuse(*_a, **_k):
raise ConnectionResetError("reset by peer")
with tempfile.TemporaryDirectory() as directory, \
mock.patch.object(transfer.urllib.request, "urlopen", refuse), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
mock.patch.object(forgehttp, "_sleep", lambda _s: None), \
self.assertRaises(DownloadError) as raised:
transfer.download_file("https://example.com/a.zip", Path(directory) / "a.zip", 20)
self.assertEqual(
+4 -3
View File
@@ -17,6 +17,7 @@ from pathlib import Path
from unittest import mock
import fileless_audit
from core import forgehttp
from profiling import fileless
ROOT = Path(__file__).resolve().parent.parent
@@ -147,7 +148,7 @@ class TestCommandLine(unittest.TestCase):
def test_an_unreachable_source_fails_the_run(self):
def unreachable(name):
raise fileless.upstream.UpstreamError("HTTP 403")
raise forgehttp.UpstreamError("HTTP 403")
code, _ = self._main("open", audit=unreachable)
self.assertEqual(code, 1)
@@ -173,7 +174,7 @@ class TestCorpusIsAnswered(unittest.TestCase):
# A cold path is unread here, not absent.
try:
lines = fetch(*args, **kwargs)
except fileless.upstream.NotCachedError:
except forgehttp.NotCachedError:
return None
if lines is not None:
read.append(args[2])
@@ -190,7 +191,7 @@ class TestCorpusIsAnswered(unittest.TestCase):
hits = fileless.audit(
path.stem, str(ROOT / "emulators"), str(cache), True
)
except fileless.upstream.NotCachedError:
except forgehttp.NotCachedError:
# A cold branch tip is unread too, not a branch gone.
continue
if hits:
+2 -1
View File
@@ -14,6 +14,7 @@ from unittest import mock
from acquire import history
from core import upstream
from core import forgehttp
class ThePinnedRevisionIsInTheHistory(unittest.TestCase):
@@ -27,7 +28,7 @@ class ThePinnedRevisionIsInTheHistory(unittest.TestCase):
def fetch(url, *_a, **_k):
return next(data for sha, data in blobs.items() if f"/{sha}/" in url)
with mock.patch.object(upstream, "cached_api", api), mock.patch.object(upstream, "fetch_body", fetch):
with mock.patch.object(upstream, "cached_api", api), mock.patch.object(forgehttp, "fetch_body", fetch):
found = history.find_revision(
repo, "dists/engine-data/queen.tbl",
hashlib.md5(b"pinned").hexdigest(), "unused")
+6 -6
View File
@@ -40,7 +40,7 @@ PAYLOAD_B = b"B" * (256 * 1024)
_ONLINE = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""})
# core.upstream retries a failed transfer after a pause: the pauses are
# skipped, the retries are not.
_NO_PAUSE = mock.patch.object(largefiles.upstream, "_sleep", lambda _s: None)
_NO_PAUSE = mock.patch.object(largefiles.forgehttp, "_sleep", lambda _s: None)
# The names these tests fetch, registered as .gitignore registers an asset:
# a bare name no registered path carries is never asked of the release.
@@ -343,8 +343,8 @@ class TheOfflineSwitchHoldsEverywhere(unittest.TestCase):
under RETROBIOS_OFFLINE it listed the release and HEADed the asset."""
with tempfile.TemporaryDirectory() as tmp, mock.patch.dict(
os.environ, {"RETROBIOS_OFFLINE": "1"}
), mock.patch.object(largefiles.upstream, "fetch_body") as fetch_body, \
mock.patch.object(largefiles.upstream, "open_retrying") as head:
), mock.patch.object(largefiles.forgehttp, "fetch_body") as fetch_body, \
mock.patch.object(largefiles.forgehttp, "open_retrying") as head:
Path(tmp, "asset.bin").write_bytes(PAYLOAD_A)
self.assertIsNone(largefiles.fetch_large_file(
"asset.bin", dest_dir=tmp,
@@ -960,10 +960,10 @@ class AFailedReleaseListingIsAskedAgain(unittest.TestCase):
run, and every asset fell back to its Content-Length."""
def test_the_listing_is_read_again_after_a_failure(self):
from core import upstream
from core import forgehttp
release = {"assets": [{"name": "a.zip", "digest": "sha256:ABC"}]}
answers = [upstream.UpstreamError("reset"), json.dumps(release).encode()]
answers = [forgehttp.UpstreamError("reset"), json.dumps(release).encode()]
def fetch_body(*_args, **_kwargs):
answer = answers.pop(0)
@@ -972,7 +972,7 @@ class AFailedReleaseListingIsAskedAgain(unittest.TestCase):
return answer
with mock.patch.object(largefiles, "_digests_cache", None), \
mock.patch.object(upstream, "fetch_body", fetch_body):
mock.patch.object(forgehttp, "fetch_body", fetch_body):
self.assertEqual(largefiles._served_digests(), {})
self.assertEqual(largefiles._served_digests(), {"a.zip": "abc"})
+2 -1
View File
@@ -13,6 +13,7 @@ import tempfile
import unittest
from pathlib import Path
from core import forgehttp
from profiling import mamerefs
from profiling.mamerefs import declares
@@ -121,7 +122,7 @@ class TestCorpusStaysCorrect(unittest.TestCase):
findings, agreed, _ = mamerefs.audit(
name, str(ROOT / "emulators"), str(cache), True
)
except mamerefs.upstream.NotCachedError as exc:
except forgehttp.NotCachedError as exc:
# A cache that holds some drivers and not others is as
# cold as an empty one for this profile.
self.skipTest(f"{name}: {exc}")
+4 -2
View File
@@ -16,6 +16,8 @@ from pathlib import Path
from unittest import mock
from core import upstream
from core import forgehttp
from core import upstreamtree
from freshness.findings import OK, SKIPPED, STALE
from freshness.pinbuilds import build_variable, check_pin_builds, pin_build_revision
@@ -104,14 +106,14 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase):
profiles = {"amiberry": {"pin_frozen": "x", "pin_build": [ref]}}
with mock.patch.object(upstream, "fetch_file", side_effect=fetch), \
mock.patch.object(upstream, "list_gitlinks", return_value={"batocera": "c" * 40}):
mock.patch.object(upstreamtree, "list_gitlinks", return_value={"batocera": "c" * 40}):
(row,) = check_pin_builds(profiles, self.platforms, "cache", False)
self.assertEqual(row.status, OK, row.detail)
def test_offline_and_uncached_is_skipped(self):
self._platform("10.2")
profiles = {"mame0278": {"pin_frozen": "x", "pin_build": [self.REF]}}
cold = upstream.NotCachedError("not cached")
cold = forgehttp.NotCachedError("not cached")
with mock.patch.object(upstream, "fetch_file", side_effect=cold):
(row,) = check_pin_builds(profiles, self.platforms, "cache", True)
self.assertEqual(row.status, SKIPPED)
+84 -82
View File
@@ -76,8 +76,10 @@ from profiling.rebase import Recale, rebase_refs
from profiling.repos import select_repo
from model.sourceref import RefPart, parse_source_ref, split_source_ref
from core import upstream
from core import forgehttp
from core import upstreamtree
from profiling import versionbasis
from core.upstream import CompareResult, FileChange
from core.upstreamtree import CompareResult, FileChange
def _version_read_as_written(profile, cache_dir, offline, profiles=None, recompute=False):
@@ -325,7 +327,7 @@ class TestSourceMirror(unittest.TestCase):
"source_commit": "87b176a",
"upstream_commit": "07021f0",
}
with tempfile.TemporaryDirectory() as cache, self.assertRaises(upstream.NotCachedError):
with tempfile.TemporaryDirectory() as cache, self.assertRaises(forgehttp.NotCachedError):
profiling_repos.select_views(profile, cache, True)
def test_a_profile_without_a_mirror_is_unchanged(self):
@@ -1291,22 +1293,22 @@ class TestBuildReport(unittest.TestCase):
upstream.fetch_file,
upstream.resolve_head,
upstream.resolve_commit_at,
upstream.compare,
upstream.list_tree,
upstreamtree.compare,
upstreamtree.list_tree,
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
upstream.http_json,
upstream.http_text,
upstream.list_gitlinks,
forgehttp.http_json,
forgehttp.http_text,
upstreamtree.list_gitlinks,
upstream.current_slug,
upstream.fork_base,
upstream.ancestry,
upstreamtree.fork_base,
upstreamtree.ancestry,
)
# Pin and tip are unrelated shas in these fixtures: no ancestry.
upstream.ancestry = lambda *a, **k: None
upstreamtree.ancestry = lambda *a, **k: None
self.fork_bases: dict[str, str] = {}
upstream.fork_base = (
upstreamtree.fork_base = (
lambda repo, sha, fork, fork_sha, cache_dir, offline=False:
self.fork_bases.get(fork_sha)
)
@@ -1318,7 +1320,7 @@ class TestBuildReport(unittest.TestCase):
)
self.tags: list[str] = []
self.gitlinks: dict[str, dict[str, str]] = {}
upstream.list_gitlinks = (
upstreamtree.list_gitlinks = (
lambda repo, sha, cache_dir, offline=False: self.gitlinks.get(sha, {})
)
self.tag_commits: dict[str, str] = {}
@@ -1326,8 +1328,8 @@ class TestBuildReport(unittest.TestCase):
def _no_network(url):
raise AssertionError(f"test reached the network: {url}")
upstream.http_json = _no_network
upstream.http_text = _no_network
forgehttp.http_json = _no_network
forgehttp.http_text = _no_network
upstream.list_tags = (
lambda repo, cache, offline=False: self.tags
)
@@ -1337,7 +1339,7 @@ class TestBuildReport(unittest.TestCase):
upstream.tag_commit = (
lambda repo, tag, cache, offline=False: self.tag_commits.get(tag)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (
sorted({path for _, path in self.files}), False
)
@@ -1353,7 +1355,7 @@ class TestBuildReport(unittest.TestCase):
upstream.resolve_commit_at = (
lambda repo, date, cache_dir, offline=False, branch=None: "pinsha"
)
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult([], False)
)
@@ -1362,17 +1364,17 @@ class TestBuildReport(unittest.TestCase):
upstream.fetch_file,
upstream.resolve_head,
upstream.resolve_commit_at,
upstream.compare,
upstream.list_tree,
upstreamtree.compare,
upstreamtree.list_tree,
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
upstream.http_json,
upstream.http_text,
upstream.list_gitlinks,
forgehttp.http_json,
forgehttp.http_text,
upstreamtree.list_gitlinks,
upstream.current_slug,
upstream.fork_base,
upstream.ancestry,
upstreamtree.fork_base,
upstreamtree.ancestry,
) = self._orig
self.tmp.cleanup()
@@ -1410,7 +1412,7 @@ class TestBuildReport(unittest.TestCase):
"""git.eden-emu.dev answers 403 to scripts: the muted repository's
citations read "absent at HEAD" for files that exist."""
def refuse(repo, sha, path, cache_dir, offline=False):
raise upstream.UpstreamError(f"{path}: HTTP 403")
raise forgehttp.UpstreamError(f"{path}: HTTP 403")
upstream.fetch_file = refuse
with contextlib.redirect_stderr(io.StringIO()):
@@ -1423,7 +1425,7 @@ class TestBuildReport(unittest.TestCase):
"""git.eden-emu.dev truncates the HEAD tree: fs_paths.h, cited bare,
was reported GONE though it lives under src/common/fs/."""
self.files[("pinsha", "fs_paths.h")] = ["x", "hit"]
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (["other.c"], True)
)
with contextlib.redirect_stderr(io.StringIO()):
@@ -1789,7 +1791,7 @@ class TestBuildReport(unittest.TestCase):
upstream.resolve_head = (
lambda repo, cache, offline=False, branch=None: heads[repo.slug]
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (
sorted(path for revision, path in self.files if revision == sha), False
)
@@ -1836,7 +1838,7 @@ class TestBuildReport(unittest.TestCase):
# the forge's orphaned objects, and every ref read ANCHORED.
self.files[("pinsha", "a.c")] = ["x", "hit"]
self.files[("headsha", "a.c")] = ["x", "hit"]
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult([], False, True)
)
report = build_report("test", self._profile(["a.c:2"]), self.dir)
@@ -1848,7 +1850,7 @@ class TestBuildReport(unittest.TestCase):
self.files[("pinsha", "a.c")] = ["x", "hit"]
self.files[("headsha", "a.c")] = ["x", "hit"]
self.tag_commits = {"v1.6.0": "pinsha"}
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult([], False, True)
)
report = build_report("test", self._versioned("1.6.0"), self.dir)
@@ -1882,7 +1884,7 @@ class TestBuildReport(unittest.TestCase):
lambda repo, cache, offline=False, branch=None: heads[repo.slug]
)
# A tag off the tracked branch is not an orphaned pin.
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult(
[], False, repo.slug == "o/up"
)
@@ -1986,7 +1988,7 @@ class TestDeclaredDeadUpstream(TestBuildReport):
def test_a_declared_death_is_reported_as_declared(self):
def boom(*a, **k):
raise upstream.GoneError("https://h/x: HTTP 451")
raise forgehttp.GoneError("https://h/x: HTTP 451")
upstream.resolve_head = boom
report = build_report(
@@ -2000,7 +2002,7 @@ class TestDeclaredDeadUpstream(TestBuildReport):
def test_any_refusal_of_a_declared_dead_forge_agrees(self):
# citron's taken domain now resolves and fails TLS.
def tls(*a, **k):
raise upstream.UpstreamError("TLSV1_UNRECOGNIZED_NAME")
raise forgehttp.UpstreamError("TLSV1_UNRECOGNIZED_NAME")
upstream.resolve_head = tls
report = build_report("test", self._profile_with("domain taken"), self.dir)
@@ -2018,10 +2020,10 @@ class TestDeclaredDeadUpstream(TestBuildReport):
def test_an_undeclared_death_is_unchanged(self):
def boom(*a, **k):
raise upstream.GoneError("https://h/x: HTTP 451")
raise forgehttp.GoneError("https://h/x: HTTP 451")
upstream.resolve_head = boom
with self.assertRaises(upstream.GoneError):
with self.assertRaises(forgehttp.GoneError):
build_report("test", self._profile(["a.c:1"]), self.dir)
@@ -2087,7 +2089,7 @@ class TestBareNameResolvedAtThePin(TestBuildReport):
def list_tree(repo, sha, cache_dir, offline=False):
return sorted({path for rev, path in self.files if rev == sha}), False
upstream.list_tree = list_tree
upstreamtree.list_tree = list_tree
def test_a_bare_name_follows_the_file_that_moved_after_the_pin(self):
self._tree_per_revision()
@@ -2170,7 +2172,7 @@ class TestRunResilience(unittest.TestCase):
def flaky(repo, date, cache_dir, offline=False, branch=None):
self.seen.append(repo.slug)
if repo.slug == "o/bad":
raise upstream.UpstreamError("HTTP 401")
raise forgehttp.UpstreamError("HTTP 401")
return "pinsha"
upstream.resolve_commit_at = flaky
@@ -2186,12 +2188,12 @@ class TestRunResilience(unittest.TestCase):
"profiled_date": "2026-03-29",
"files": [{"name": "a.bin", "source_ref": "a.c:1"}],
}
with self.assertRaises(upstream.UpstreamError):
with self.assertRaises(forgehttp.UpstreamError):
build_report("bad", profile, self.tmp.name)
def test_rate_limit_still_propagates(self):
def limited(repo, date, cache_dir, offline=False, branch=None):
raise upstream.RateLimitError("HTTP 403")
raise forgehttp.RateLimitError("HTTP 403")
upstream.resolve_commit_at = limited
profile = {
@@ -2200,7 +2202,7 @@ class TestRunResilience(unittest.TestCase):
"profiled_date": "2026-03-29",
"files": [{"name": "a.bin", "source_ref": "a.c:1"}],
}
with self.assertRaises(upstream.RateLimitError):
with self.assertRaises(forgehttp.RateLimitError):
build_report("x", profile, self.tmp.name)
@@ -2240,7 +2242,7 @@ class TestExtrasSurviveARefusingForge(unittest.TestCase):
original = upstream.fetch_file
def refuse(*_args, **_kwargs):
raise upstream.UpstreamError("https://x/y: HTTP 403")
raise forgehttp.UpstreamError("https://x/y: HTTP 403")
upstream.fetch_file = refuse
try:
@@ -2279,11 +2281,11 @@ class TestExtrasSurviveARefusingForge(unittest.TestCase):
original = upstream.fetch_file
def quota(*_args, **_kwargs):
raise upstream.RateLimitError("quota")
raise forgehttp.RateLimitError("quota")
upstream.fetch_file = quota
try:
with self.assertRaises(upstream.RateLimitError):
with self.assertRaises(forgehttp.RateLimitError):
profiling_run._attach_detection(
self._profile(), _sample_report(), "x", False, True, False
)
@@ -2814,9 +2816,9 @@ class TestWriteDryRun(unittest.TestCase):
from unittest import mock
before = self.path.read_bytes()
cold = upstream.NotCachedError("x.c not cached")
cold = forgehttp.NotCachedError("x.c not cached")
with mock.patch.object(profiling_run, "realign_prose", side_effect=[[], cold]), \
self.assertRaises(upstream.NotCachedError):
self.assertRaises(forgehttp.NotCachedError):
self._run(self._args(rebase_refs=True, dry_run=False), self._shifted())
self.assertEqual(self.path.read_bytes(), before)
@@ -2828,7 +2830,7 @@ class TestWriteDryRun(unittest.TestCase):
before = self.path.read_bytes()
skipped = ProfileReport(name="p", entries=[], counts={}, skipped="offline: not cached",
skip_kind=SkipKind.OFFLINE)
cold = upstream.NotCachedError("o/n@pin:a.c is not in the offline cache")
cold = forgehttp.NotCachedError("o/n@pin:a.c is not in the offline cache")
reports: list[ProfileReport] = []
failed: set[str] = set()
with mock.patch.object(profiling_run, "_build_full_report", return_value=skipped), \
@@ -3787,7 +3789,7 @@ class APassedReleaseIsNewerThanTheTag(unittest.TestCase):
"v0.2.22", "v0.2.22", "v0.2.20", "2026-07-25", True, "tag22"
)
with mock.patch.object(upstream, "tag_commit", return_value="rel20"), \
mock.patch.object(upstream, "ancestry", return_value=(5, 0)):
mock.patch.object(upstreamtree, "ancestry", return_value=(5, 0)):
self.assertIsNone(versions.latest_passed_release("repo", version, "pin", "c", True))
@@ -3800,7 +3802,7 @@ class ANewerReleaseThanTheTag(unittest.TestCase):
version = versions.VersionReport("2.8", "2.9", "2.9", "2026-10-01", True, "tag28")
answers = iter([after_tag, after_pin])
with mock.patch.object(upstream, "tag_commit", return_value="rel29"), \
mock.patch.object(upstream, "ancestry", side_effect=lambda *a, **k: next(answers)):
mock.patch.object(upstreamtree, "ancestry", side_effect=lambda *a, **k: next(answers)):
return versions.newer_release("repo", version, "tag28", "c", True)
def test_a_later_release_is_named(self):
@@ -3836,7 +3838,7 @@ class AProjectThatOnlyTags(unittest.TestCase):
version = versions.VersionReport("v1.2", "v1.3", None, None, True, "tag12")
with mock.patch.object(upstream, "tag_commit", return_value="tag13"), \
mock.patch.object(upstream, "ancestry", return_value=(7, 0)):
mock.patch.object(upstreamtree, "ancestry", return_value=(7, 0)):
self.assertEqual(versions.newer_release("repo", version, "tag12", "c", True), "v1.3")
@@ -3860,7 +3862,7 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
version = versions.VersionReport(declared, release, release, "d", False, None)
with self.subTest(declared=declared, release=release), \
mock.patch.object(upstream, "tag_commit", return_value="rel"), \
mock.patch.object(upstream, "ancestry", return_value=(3, 0)):
mock.patch.object(upstreamtree, "ancestry", return_value=(3, 0)):
self.assertEqual(versions.latest_passed_release("repo", version, "pin", "c", True), expected)
def test_no_tag_and_nothing_passed_stays_quiet(self):
@@ -3872,10 +3874,10 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
class TestAncestry(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream.http_json
self.saved = forgehttp.http_json
def tearDown(self):
upstream.http_json = self.saved
forgehttp.http_json = self.saved
self.tmp.cleanup()
def test_github_answers_both_directions_at_once(self):
@@ -3885,10 +3887,10 @@ class TestAncestry(unittest.TestCase):
calls.append(url)
return {"ahead_by": 3, "behind_by": 0}
upstream.http_json = answer
forgehttp.http_json = answer
repo = upstream.parse_repo("https://github.com/o/n")
self.assertEqual(
upstream.ancestry(repo, "tag", "pin", self.tmp.name), (3, 0)
upstreamtree.ancestry(repo, "tag", "pin", self.tmp.name), (3, 0)
)
self.assertEqual(len(calls), 1)
@@ -3897,10 +3899,10 @@ class TestAncestry(unittest.TestCase):
forward = "from=tag&to=pin" in url
return {"commits": [{}] * (0 if forward else 5)}
upstream.http_json = answer
forgehttp.http_json = answer
repo = upstream.parse_repo("https://gitlab.com/o/n")
self.assertEqual(
upstream.ancestry(repo, "tag", "pin", self.tmp.name), (0, 5)
upstreamtree.ancestry(repo, "tag", "pin", self.tmp.name), (0, 5)
)
@@ -4316,10 +4318,10 @@ class TestCollectCitations(unittest.TestCase):
with mock.patch.object(upstream, "fetch_file", side_effect=fetch), \
mock.patch.object(
upstream, "list_gitlinks",
upstreamtree, "list_gitlinks",
return_value={"Q3E/src/main/jni/xash3d/xash3d-fwgs": "s1"},
):
target = upstream.through_gitlink(
target = upstreamtree.through_gitlink(
port, "p1",
"Q3E/src/main/jni/xash3d/xash3d-fwgs/filesystem/filesystem.c", "c",
)
@@ -4868,14 +4870,14 @@ class TestRealignProse(unittest.TestCase):
self.files: dict[tuple[str, str], list[str]] = {}
self._orig = (
upstream.fetch_file,
upstream.list_tree,
upstreamtree.list_tree,
)
upstream.fetch_file = (
lambda repo, sha, path, cache_dir, offline=False: self.files.get(
(sha, path)
)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (
sorted({p for _, p in self.files}), False
)
@@ -4884,7 +4886,7 @@ class TestRealignProse(unittest.TestCase):
def tearDown(self):
(
upstream.fetch_file,
upstream.list_tree,
upstreamtree.list_tree,
) = self._orig
self.tmp.cleanup()
@@ -5190,7 +5192,7 @@ class TestRealignProse(unittest.TestCase):
base = PROSE_SAMPLE.replace("(a.c:10)", "(deep.c:10)")
self._commit(base.replace('"pin"', '"oldpin"'), "profile")
self.path.write_text(base, encoding="utf-8")
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: ([], True)
)
self.files[("oldpin", "b.c")] = list("pqrstuvwx")
@@ -5242,7 +5244,7 @@ class TestRateLimitEndsOneProfile(unittest.TestCase):
def build(name, *_args, **_kwargs):
if name == "cemu":
raise upstream.RateLimitError(
raise forgehttp.RateLimitError(
"https://git.libretro.com/x: HTTP 429", "git.libretro.com"
)
return ProfileReport(name=name, counts={"CHANGED": 1})
@@ -5593,7 +5595,7 @@ class TestOutputModesApplyTheirFlags(unittest.TestCase):
def build(name, *args, **kwargs):
if name == "drift":
raise upstream.UpstreamError("https://x: HTTP 502")
raise forgehttp.UpstreamError("https://x: HTTP 502")
return ProfileReport(name=name)
out = io.StringIO()
@@ -5798,7 +5800,7 @@ class UpstreamVendoredAsASubmodule(unittest.TestCase):
profiling_repos.RepoView(repo_u, "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstream, "list_gitlinks",
upstreamtree, "list_gitlinks",
side_effect=lambda repo, sha, *a, **k: links.get(sha, {}),
):
return profiling_repos._follow_submodule(views, "cache", True)
@@ -5820,9 +5822,9 @@ class UpstreamVendoredAsASubmodule(unittest.TestCase):
profiling_repos.RepoView(object(), "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstream, "list_gitlinks",
side_effect=upstream.TruncatedListingError("tree listing truncated"),
), self.assertRaises(upstream.TruncatedListingError):
upstreamtree, "list_gitlinks",
side_effect=forgehttp.TruncatedListingError("tree listing truncated"),
), self.assertRaises(forgehttp.TruncatedListingError):
profiling_repos._follow_submodule(views, "cache", True)
@@ -5837,10 +5839,10 @@ class TruncatedGitlinksInTheResolver(unittest.TestCase):
def links(repo, sha, *_args):
if repo == "a":
raise upstream.TruncatedListingError("a@p1: tree listing truncated")
raise forgehttp.TruncatedListingError("a@p1: tree listing truncated")
return {"sub": "s"}
with mock.patch.object(upstream, "list_gitlinks", side_effect=links), \
with mock.patch.object(upstreamtree, "list_gitlinks", side_effect=links), \
contextlib.redirect_stderr(io.StringIO()) as err:
found = [list(paths) for paths in resolver._Resolver.gitlinks_in_order(state)]
self.assertEqual(found, [[], ["sub"]])
@@ -5859,7 +5861,7 @@ class AMirrorOutlivesAGoneSource(unittest.TestCase):
def head(repo, cache_dir, offline=False, branch=None):
if repo == gone_repo:
raise upstream.GoneError("HTTP 451")
raise forgehttp.GoneError("HTTP 451")
return "mirror-head"
profile = {
@@ -5883,7 +5885,7 @@ class AMirrorOutlivesAGoneSource(unittest.TestCase):
def head(repo, cache_dir, offline=False, branch=None):
if repo == gone_repo:
raise upstream.GoneError("HTTP 404")
raise forgehttp.GoneError("HTTP 404")
return "tip"
profile = {
@@ -6042,9 +6044,9 @@ class UpstreamForkedByThePort(unittest.TestCase):
profiling_repos.RepoView(self.up, "old-base", "up-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstream, "fork_base", return_value=base
upstreamtree, "fork_base", return_value=base
) as asked, mock.patch.object(
upstream, "ancestry", return_value=ancestry
upstreamtree, "ancestry", return_value=ancestry
):
followed = profiling_repos._follow_fork_base(views, "cache", True)
return followed, asked
@@ -6077,7 +6079,7 @@ class ACachedTipOlderThanThePin(TestBuildReport):
77d80d7, its ancestor: a bump would have moved the pin backwards."""
def test_the_tip_is_asked_again(self):
upstream.ancestry = lambda *a, **k: (0, 3)
upstreamtree.ancestry = lambda *a, **k: (0, 3)
upstream.resolve_head = (
lambda repo, cache_dir, offline=False, branch=None, fresh=False:
"newtip" if fresh else "staletip"
@@ -6095,10 +6097,10 @@ class OfflineCacheMissIsNotGone(TestBuildReport):
def test_an_uncached_file_is_not_reported_gone(self):
def cold(repo, sha, path, cache_dir, offline=False):
raise upstream.NotCachedError(f"{path} not cached")
raise forgehttp.NotCachedError(f"{path} not cached")
upstream.fetch_file = cold
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
build_report("test", self._profile(["a.c:2"]), self.dir, offline=True)
@@ -6287,10 +6289,10 @@ class AnOffForgeProfileWatchesItsReleasePage(unittest.TestCase):
"url": "https://example.test/altirra", "pattern": r"Altirra (\d+\.\d+) released",
}}
answers = [
(upstream.NotCachedError("cold"), "not cached offline"),
(forgehttp.NotCachedError("cold"), "not cached offline"),
(None, "page absent"),
("<p>nothing here</p>", "pattern not found"),
(upstream.UpstreamError("HTTP 500"), "https://example.test/altirra: HTTP 500"),
(forgehttp.UpstreamError("HTTP 500"), "https://example.test/altirra: HTTP 500"),
]
for answer, reason in answers:
effect = {"side_effect": answer} if isinstance(answer, Exception) else {"return_value": answer}
@@ -6301,7 +6303,7 @@ class AnOffForgeProfileWatchesItsReleasePage(unittest.TestCase):
stderr.write.assert_not_called()
def test_an_uncached_page_offline_is_not_an_absent_one(self):
with tempfile.TemporaryDirectory() as cache, self.assertRaises(upstream.NotCachedError):
with tempfile.TemporaryDirectory() as cache, self.assertRaises(forgehttp.NotCachedError):
upstream.fetch_page("https://example.invalid/never-cached", cache, True)
def test_the_reason_reaches_the_json_and_the_text(self):
@@ -6366,7 +6368,7 @@ class EachCitationNamesTheCodeThatAsks(unittest.TestCase):
lambda repo, sha, path, cache_dir, offline=False:
trees.get(repo.slug, {}).get(path)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (sorted(trees[repo.slug]), False)
)
upstream.resolve_head = (
@@ -6414,7 +6416,7 @@ class ARoleIsReadPerPart(unittest.TestCase):
lambda repo, sha, path, cache_dir, offline=False:
trees.get((repo.slug, sha), {}).get(path)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False:
(sorted(trees.get((repo.slug, sha), {})), False)
)
@@ -6422,9 +6424,9 @@ class ARoleIsReadPerPart(unittest.TestCase):
lambda repo, cache_dir, offline=False, branch=None:
"heads" if repo.owner == "libretro" else "pinu"
)
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False:
upstream.CompareResult([], False)
upstreamtree.CompareResult([], False)
)
text = (
'emulator: T\n'
+2 -1
View File
@@ -451,6 +451,7 @@ class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase):
def _resolve(self, url: str, version: str, answers: list) -> tuple[str | None, list]:
from core import upstream
from core import forgehttp
seen: list = []
@@ -464,7 +465,7 @@ class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase):
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp, \
mock.patch.object(upstream, "CACHE_DIR", tmp), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
mock.patch.object(forgehttp, "_sleep", lambda _s: None), \
mock.patch.dict("os.environ", {"GITHUB_TOKEN": "SECRET"}), \
mock.patch("urllib.request.urlopen", urlopen):
return datadirs.get_remote_sha(url, version), seen
+2 -1
View File
@@ -298,9 +298,10 @@ class CachedDirectory(unittest.TestCase):
from unittest import mock
from core import upstream
from core import upstreamtree
fetcher = Fetcher({"os": {"repo": "https://gitlab.com/g/p", "commit": "0" * 40}})
with mock.patch.object(upstream, "cache_gitlab_directory", return_value={"sys/a/system.ini"}):
with mock.patch.object(upstreamtree, "cache_gitlab_directory", return_value={"sys/a/system.ini"}):
fetcher.cache_directory("os", "sys/")
with mock.patch.object(upstream, "fetch_file", side_effect=AssertionError("network")):
self.assertIsNone(fetcher.optional_text("os", "sys/b/system.ini"))
+7 -7
View File
@@ -159,19 +159,19 @@ class RateLimitedForge(unittest.TestCase):
return urllib.error.HTTPError("u", 429, "Too Many Requests", headers, io.BytesIO())
def setUp(self):
from core import upstream
from core import forgehttp
self.waits: list[float] = []
patcher = mock.patch.object(upstream, "_sleep", self.waits.append)
patcher = mock.patch.object(forgehttp, "_sleep", self.waits.append)
patcher.start()
self.addCleanup(patcher.stop)
upstream._exhausted_hosts.clear()
self.addCleanup(upstream._exhausted_hosts.clear)
forgehttp._exhausted_hosts.clear()
self.addCleanup(forgehttp._exhausted_hosts.clear)
def test_a_rate_limit_is_waited_out(self):
import io
from core import upstream
from core import forgehttp
from scraper.base_scraper import fetch_bytes
answers = [self._limited("7"), self._limited(None), io.BytesIO(b"ok")]
@@ -184,7 +184,7 @@ class RateLimitedForge(unittest.TestCase):
with mock.patch("urllib.request.urlopen", urlopen):
self.assertEqual(fetch_bytes("https://x"), b"ok")
self.assertEqual(self.waits, [7.0, upstream.RATE_LIMIT_WAITS[1]])
self.assertEqual(self.waits, [7.0, forgehttp.RATE_LIMIT_WAITS[1]])
def test_a_lasting_limit_or_a_missing_file_fails(self):
from scraper.base_scraper import FetchError, fetch_bytes
@@ -987,7 +987,7 @@ class EveryGitHubApiCallerSendsTheToken(unittest.TestCase):
# arcade_parent_importer names API URLs and sends them through
# dat_fetch.api_json, which holds the token, and the
# scrapers through base_scraper.github_json, the rest through
# core.upstream.fetch_body or forge_headers.
# core.forgehttp.fetch_body or forge_headers.
and ("Request(" in source or "urlopen(" in source or path.suffix == ".sh")
and "GITHUB_TOKEN" not in source
and "github_headers(" not in source
+1 -1
View File
@@ -276,7 +276,7 @@ class OneImplementationPerJob(unittest.TestCase):
for needle in needles
if needle in path.read_text(encoding="utf-8")
]
# The ETag HEAD probe is core.upstream.remote_etag. MinUI reads
# The ETag HEAD probe is core.forgehttp.remote_etag. MinUI reads
# through a fetch its tests replace, and hands the answer to
# tree_entries.
self.assertEqual(found, ["minui_scraper.py: ?recursive=1"])
+4 -4
View File
@@ -292,8 +292,8 @@ class GoatCounterExport(unittest.TestCase):
refusal = urllib.error.HTTPError("https://retrobios.goatcounter.com/api/v0/stats/hits", 429,
"Too Many Requests", headers, io.BytesIO(b""))
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=refusal), \
mock.patch.object(insights.upstream, "_sleep") as sleep, \
mock.patch.object(insights.upstream, "_exhausted_hosts", set()), \
mock.patch.object(insights.forgehttp, "_sleep") as sleep, \
mock.patch.object(insights.forgehttp, "_exhausted_hosts", set()), \
self.assertRaisesRegex(insights.SourceUnavailable, "2356 s") as caught:
insights._get_json("https://retrobios.goatcounter.com/api/v0/stats/hits")
sleep.assert_not_called()
@@ -307,7 +307,7 @@ class GoatCounterExport(unittest.TestCase):
answer.__enter__.return_value.status = 200
answer.__enter__.return_value.read.return_value = json.dumps({"ok": 1}).encode()
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \
mock.patch.object(insights.upstream, "_sleep") as sleep:
mock.patch.object(insights.forgehttp, "_sleep") as sleep:
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
sleep.assert_called_once_with(2)
@@ -319,7 +319,7 @@ class GoatCounterExport(unittest.TestCase):
answer.__enter__.return_value.status = 200
answer.__enter__.return_value.read.return_value = json.dumps({"ok": 1}).encode()
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \
mock.patch.object(insights.upstream, "_sleep"):
mock.patch.object(insights.forgehttp, "_sleep"):
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
def test_github_headers_come_from_the_forge_helper(self) -> None:
+3 -2
View File
@@ -86,6 +86,7 @@ import core
from sitegen import sources
from model import releaserecord
from core import upstream
from core import forgehttp
from packs.verdicts import Severity, blocking_missing, compute_severity
from acquire.provenance import build_report
from model.dumpcatalog import load_provenance_snapshots
@@ -1189,8 +1190,8 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40,
"files": [{"source_ref": "src/a.c:5"}]}
with mock.patch.object(sources, "_cached_tree", return_value=None), \
mock.patch.object(core.upstream, "list_directory",
side_effect=upstream.UpstreamError("HTTP 404")):
mock.patch.object(core.upstreamtree, "list_directory",
side_effect=forgehttp.UpstreamError("HTTP 404")):
held, unread = sources.build_source_paths({"p": profile}, [TMP])
self.assertEqual(held, {})
self.assertEqual(unread, ["github.com/o/r@" + "e" * 40])
+3 -2
View File
@@ -21,6 +21,7 @@ from unittest import mock
from model import sourceref
from sitegen import sources
from core import upstream
from core import upstreamtree
from model.profiles import load_emulator_profiles
from model.sourceref import ref_role, source_ref_values, split_source_ref
@@ -78,7 +79,7 @@ class ForgejoTreesArePaged(unittest.TestCase):
return {"tree": pages.get(page, []), "truncated": True, "total_count": 1002}
with mock.patch.object(upstream, "cached_api", side_effect=fake_api):
paths, truncated = upstream.list_tree(repo, "7" * 40, "unused")
paths, truncated = upstreamtree.list_tree(repo, "7" * 40, "unused")
self.assertFalse(truncated)
self.assertEqual(len(paths), 1001)
self.assertIn("src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs", paths)
@@ -87,7 +88,7 @@ class ForgejoTreesArePaged(unittest.TestCase):
repo = upstream.parse_repo("https://github.com/o/r")
payload = {"tree": [{"type": "blob", "path": "x"}], "truncated": True}
with mock.patch.object(upstream, "cached_api", return_value=payload) as api:
paths, truncated = upstream.list_tree(repo, "7" * 40, "unused")
paths, truncated = upstreamtree.list_tree(repo, "7" * 40, "unused")
self.assertTrue(truncated)
self.assertEqual(api.call_count, 1)
+4 -4
View File
@@ -974,13 +974,13 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
run.assert_not_called()
def test_every_api_caller_reads_it(self):
from core import upstream
from core import forgehttp
from profiling.quota import check_quota
from scraper import base_scraper
with self._gh():
self.assertEqual(
upstream.forge_headers("https://api.github.com/repos/o/n")["Authorization"],
forgehttp.forge_headers("https://api.github.com/repos/o/n")["Authorization"],
"Bearer gho_fromgh",
)
os.environ.pop("GITHUB_TOKEN")
@@ -992,10 +992,10 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
check_quota(606, offline=False)
def test_another_forge_never_triggers_gh(self):
from core import upstream
from core import forgehttp
with self._gh() as run:
headers = upstream.forge_headers("https://gitlab.com/api/v4/projects/1")
headers = forgehttp.forge_headers("https://gitlab.com/api/v4/projects/1")
self.assertNotIn("Authorization", headers)
run.assert_not_called()
+170 -168
View File
@@ -17,6 +17,8 @@ import urllib.request
from pathlib import Path
from core import upstream
from core import forgehttp
from core import upstreamtree
from core.upstream import make_repo, parse_repo, raw_url
@@ -169,43 +171,43 @@ class TestTokenScope(unittest.TestCase):
os.environ["GITHUB_TOKEN"] = self._orig
def test_sent_to_github_api(self):
h = upstream.forge_headers("https://api.github.com/repos/o/n/commits")
h = forgehttp.forge_headers("https://api.github.com/repos/o/n/commits")
self.assertEqual(h["Authorization"], "Bearer gho_secret")
def test_sent_to_github_raw(self):
h = upstream.forge_headers("https://raw.githubusercontent.com/o/n/sha/a.c")
h = forgehttp.forge_headers("https://raw.githubusercontent.com/o/n/sha/a.c")
self.assertIn("Authorization", h)
def test_withheld_from_codeberg(self):
h = upstream.forge_headers("https://codeberg.org/api/v1/repos/o/n/commits")
h = forgehttp.forge_headers("https://codeberg.org/api/v1/repos/o/n/commits")
self.assertNotIn("Authorization", h)
def test_withheld_from_gitlab(self):
h = upstream.forge_headers("https://gitlab.com/api/v4/projects/x/repository/commits")
h = forgehttp.forge_headers("https://gitlab.com/api/v4/projects/x/repository/commits")
self.assertNotIn("Authorization", h)
def test_withheld_from_forgejo_instances(self):
for host in ("git.citron-emu.org", "git.eden-emu.dev", "git.ryujinx.app"):
h = upstream.forge_headers(f"https://{host}/api/v1/repos/o/n/commits")
h = forgehttp.forge_headers(f"https://{host}/api/v1/repos/o/n/commits")
self.assertNotIn("Authorization", h, host)
def test_withheld_from_a_lookalike_host(self):
h = upstream.forge_headers("https://github.com.evil.example/repos/o/n")
h = forgehttp.forge_headers("https://github.com.evil.example/repos/o/n")
self.assertNotIn("Authorization", h)
def test_withheld_from_a_url_that_only_names_the_api(self):
h = upstream.forge_headers("https://evil.example/x?next=https://api.github.com/")
h = forgehttp.forge_headers("https://evil.example/x?next=https://api.github.com/")
self.assertNotIn("Authorization", h)
def test_withheld_from_the_web_host(self):
# A release download on github.com redirects to asset storage, and
# urllib carries the header across the redirect.
h = upstream.forge_headers("https://github.com/o/n/releases/download/v1/a.zip")
h = forgehttp.forge_headers("https://github.com/o/n/releases/download/v1/a.zip")
self.assertNotIn("Authorization", h)
def test_absent_token_adds_no_header(self):
os.environ.pop("GITHUB_TOKEN", None)
h = upstream.forge_headers("https://api.github.com/repos/o/n")
h = forgehttp.forge_headers("https://api.github.com/repos/o/n")
self.assertNotIn("Authorization", h)
@@ -214,34 +216,34 @@ class TestHttpFailure(unittest.TestCase):
def test_429_is_a_rate_limit(self):
self.assertIsInstance(
upstream._http_failure("u", _http_error(429)), upstream.RateLimitError
forgehttp._http_failure("u", _http_error(429)), forgehttp.RateLimitError
)
def test_429_names_the_wait_the_forge_asks_for(self):
failure = upstream._http_failure("u", _http_error(429, {"Retry-After": "1833"}))
failure = forgehttp._http_failure("u", _http_error(429, {"Retry-After": "1833"}))
self.assertIn("retry after 1833 s", str(failure))
def test_403_with_exhausted_quota_is_a_rate_limit(self):
exc = _http_error(403, {"X-RateLimit-Remaining": "0"})
self.assertIsInstance(
upstream._http_failure("u", exc), upstream.RateLimitError
forgehttp._http_failure("u", exc), forgehttp.RateLimitError
)
def test_403_with_quota_left_is_not(self):
exc = _http_error(403, {"X-RateLimit-Remaining": "4970"})
failure = upstream._http_failure("u", exc)
self.assertIsInstance(failure, upstream.UpstreamError)
self.assertNotIsInstance(failure, upstream.RateLimitError)
failure = forgehttp._http_failure("u", exc)
self.assertIsInstance(failure, forgehttp.UpstreamError)
self.assertNotIsInstance(failure, forgehttp.RateLimitError)
def test_bare_403_from_a_forge_is_not_a_rate_limit(self):
failure = upstream._http_failure("u", _http_error(403))
self.assertIsInstance(failure, upstream.UpstreamError)
self.assertNotIsInstance(failure, upstream.RateLimitError)
failure = forgehttp._http_failure("u", _http_error(403))
self.assertIsInstance(failure, forgehttp.UpstreamError)
self.assertNotIsInstance(failure, forgehttp.RateLimitError)
def test_525_is_a_plain_upstream_error(self):
failure = upstream._http_failure("u", _http_error(525))
self.assertIsInstance(failure, upstream.UpstreamError)
self.assertNotIsInstance(failure, upstream.RateLimitError)
failure = forgehttp._http_failure("u", _http_error(525))
self.assertIsInstance(failure, forgehttp.UpstreamError)
self.assertNotIsInstance(failure, forgehttp.RateLimitError)
@tests.ONLINE
@@ -249,14 +251,14 @@ class TestFetchRetry(unittest.TestCase):
"""Transient network failures are retried, definitive answers are not."""
def setUp(self):
self._orig = (urllib.request.urlopen, upstream._sleep)
self._orig = (urllib.request.urlopen, forgehttp._sleep)
self.slept: list[float] = []
upstream._sleep = self.slept.append
upstream._exhausted_hosts.clear()
forgehttp._sleep = self.slept.append
forgehttp._exhausted_hosts.clear()
def tearDown(self):
urllib.request.urlopen, upstream._sleep = self._orig
upstream._exhausted_hosts.clear()
urllib.request.urlopen, forgehttp._sleep = self._orig
forgehttp._exhausted_hosts.clear()
def _serve(self, outcomes):
self.calls = 0
@@ -273,31 +275,31 @@ class TestFetchRetry(unittest.TestCase):
def test_dropped_connection_is_retried_then_succeeds(self):
dropped = http.client.RemoteDisconnected("closed")
self._serve([dropped, b"payload"])
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(forgehttp.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.calls, 2)
self.assertEqual(len(self.slept), 1)
def test_retries_are_bounded(self):
self._serve([http.client.RemoteDisconnected("closed")])
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, upstream.RETRIES)
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, forgehttp.RETRIES)
def test_server_error_is_retried(self):
self._serve([_http_error(503)])
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, upstream.RETRIES)
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, forgehttp.RETRIES)
def test_forbidden_is_not_retried(self):
self._serve([_http_error(403)])
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
def test_missing_file_is_not_retried(self):
self._serve([_http_error(404)])
self.assertIsNone(upstream.fetch_body("https://host/x"))
self.assertIsNone(forgehttp.fetch_body("https://host/x"))
self.assertEqual(self.calls, 1)
@staticmethod
@@ -313,26 +315,26 @@ class TestFetchRetry(unittest.TestCase):
# git.libretro.com answered 429 on cemu's tree a few hundred
# requests into a pass, and the whole pass stopped.
self._serve([self._limited("7"), self._limited(), b"payload"])
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [7.0, upstream.RATE_LIMIT_WAITS[1]])
self.assertEqual(forgehttp.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [7.0, forgehttp.RATE_LIMIT_WAITS[1]])
def test_lasting_rate_limit_mutes_the_host_only(self):
self._serve([self._limited()])
with self.assertRaises(upstream.RateLimitError) as caught:
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.RateLimitError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertEqual(caught.exception.host, "host")
self.assertEqual(self.calls, len(upstream.RATE_LIMIT_WAITS) + 1)
self.assertEqual(self.calls, len(forgehttp.RATE_LIMIT_WAITS) + 1)
# The same host is not asked again, another one still is.
with self.assertRaises(upstream.RateLimitError):
upstream.fetch_body("https://host/y")
self.assertEqual(self.calls, len(upstream.RATE_LIMIT_WAITS) + 1)
with self.assertRaises(forgehttp.RateLimitError):
forgehttp.fetch_body("https://host/y")
self.assertEqual(self.calls, len(forgehttp.RATE_LIMIT_WAITS) + 1)
self._serve([b"other"])
self.assertEqual(upstream.fetch_body("https://other/x"), b"other")
self.assertEqual(forgehttp.fetch_body("https://other/x"), b"other")
def test_long_retry_after_is_not_waited(self):
self._serve([self._limited(str(int(upstream.RATE_LIMIT_WAIT_CAP) + 1))])
with self.assertRaises(upstream.RateLimitError):
upstream.fetch_body("https://host/x")
self._serve([self._limited(str(int(forgehttp.RATE_LIMIT_WAIT_CAP) + 1))])
with self.assertRaises(forgehttp.RateLimitError):
forgehttp.fetch_body("https://host/x")
self.assertEqual((self.calls, self.slept), (1, []))
def test_goatcounter_reset_header_is_waited_with_a_second_more(self):
@@ -341,7 +343,7 @@ class TestFetchRetry(unittest.TestCase):
headers = email.message.Message()
headers["X-Rate-Limit-Reset"] = "3"
self._serve([_http_error(429, headers), b"payload"])
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(forgehttp.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [4.0])
def test_download_retries_a_cut_stream_and_writes_whole(self):
@@ -359,7 +361,7 @@ class TestFetchRetry(unittest.TestCase):
urllib.request.urlopen = opener
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "file.bin"
served = upstream.download("https://host/file.bin", target)
served = forgehttp.download("https://host/file.bin", target)
self.assertEqual(target.read_bytes(), b"payload")
self.assertEqual(served["Content-Disposition"], "attachment")
self.assertEqual(os.listdir(tmp), ["file.bin"])
@@ -375,7 +377,7 @@ class TestFetchRetry(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "file.bin"
target.write_bytes(b"old")
self.assertIsNone(upstream.download("https://host/f", target, accept=lambda _p: False))
self.assertIsNone(forgehttp.download("https://host/f", target, accept=lambda _p: False))
self.assertEqual(target.read_bytes(), b"old")
self.assertEqual(os.listdir(tmp), ["file.bin"])
@@ -388,7 +390,7 @@ class TestFetchRetry(unittest.TestCase):
urllib.request.urlopen = opener
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaises(ValueError):
upstream.download("https://host/f", Path(tmp) / "f", max_bytes=4)
forgehttp.download("https://host/f", Path(tmp) / "f", max_bytes=4)
self.assertEqual(os.listdir(tmp), [])
def test_exhausted_github_quota_is_not_waited(self):
@@ -397,8 +399,8 @@ class TestFetchRetry(unittest.TestCase):
headers = email.message.Message()
headers["X-RateLimit-Remaining"] = "0"
self._serve([_http_error(403, headers)])
with self.assertRaises(upstream.RateLimitError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.RateLimitError):
forgehttp.fetch_body("https://host/x")
self.assertEqual((self.calls, self.slept), (1, []))
@@ -413,13 +415,13 @@ class TestGoneUpstream(unittest.TestCase):
"""
def setUp(self):
self._orig = (urllib.request.urlopen, upstream._sleep)
self._orig = (urllib.request.urlopen, forgehttp._sleep)
self.slept: list[float] = []
upstream._sleep = self.slept.append
forgehttp._sleep = self.slept.append
self.calls = 0
def tearDown(self):
urllib.request.urlopen, upstream._sleep = self._orig
urllib.request.urlopen, forgehttp._sleep = self._orig
def _serve(self, outcome):
def opener(req, timeout=None):
@@ -430,24 +432,24 @@ class TestGoneUpstream(unittest.TestCase):
def test_legal_takedown_is_gone_and_not_retried(self):
self._serve(_http_error(451))
with self.assertRaises(upstream.GoneError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.GoneError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
self.assertEqual(self.slept, [])
def test_http_gone_is_gone(self):
self._serve(_http_error(410))
with self.assertRaises(upstream.GoneError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.GoneError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
def test_unresolvable_host_is_gone_and_not_retried(self):
self._serve(urllib.error.URLError(
socket.gaierror(socket.EAI_NONAME, "Name or service not known")
))
with mock.patch.object(upstream, "_resolver_answers", return_value=True), \
self.assertRaises(upstream.GoneError):
upstream.fetch_body("https://host/x")
with mock.patch.object(forgehttp, "_resolver_answers", return_value=True), \
self.assertRaises(forgehttp.GoneError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
self.assertEqual(self.slept, [])
@@ -457,29 +459,29 @@ class TestGoneUpstream(unittest.TestCase):
for errno, resolver in ((socket.EAI_NONAME, False), (socket.EAI_AGAIN, True)):
with self.subTest(errno=errno, resolver=resolver):
self._serve(urllib.error.URLError(socket.gaierror(errno, "no")))
with mock.patch.object(upstream, "_resolver_answers", return_value=resolver), \
self.assertRaises(upstream.UpstreamError) as caught:
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
with mock.patch.object(forgehttp, "_resolver_answers", return_value=resolver), \
self.assertRaises(forgehttp.UpstreamError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, forgehttp.GoneError)
def test_a_gone_error_is_still_an_upstream_error(self):
self._serve(_http_error(451))
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
def test_refused_request_is_not_gone(self):
"""403 is a forge refusing a request, which anti-bot filters do."""
self._serve(_http_error(403))
with self.assertRaises(upstream.UpstreamError) as caught:
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
with self.assertRaises(forgehttp.UpstreamError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, forgehttp.GoneError)
def test_a_dropped_connection_is_not_gone(self):
self._serve(http.client.RemoteDisconnected("closed"))
with self.assertRaises(upstream.UpstreamError) as caught:
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
self.assertEqual(self.calls, upstream.RETRIES)
with self.assertRaises(forgehttp.UpstreamError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, forgehttp.GoneError)
self.assertEqual(self.calls, forgehttp.RETRIES)
@@ -501,10 +503,10 @@ class TheOfflineSwitchHoldsAtTheGateway(unittest.TestCase):
def test_no_request_goes_out(self):
with mock.patch.object(urllib.request, "urlopen", side_effect=_no_network) as urlopen:
with self.assertRaises(upstream.OfflineError):
upstream.fetch_body("https://api.github.com/rate_limit", accept_json=True)
with self.assertRaises(upstream.NotCachedError):
upstream.download("https://host/x", tests.scratch_dir(self) / "x")
with self.assertRaises(forgehttp.OfflineError):
forgehttp.fetch_body("https://api.github.com/rate_limit", accept_json=True)
with self.assertRaises(forgehttp.NotCachedError):
forgehttp.download("https://host/x", tests.scratch_dir(self) / "x")
urlopen.assert_not_called()
def test_a_file_address_is_read_offline(self):
@@ -513,14 +515,14 @@ class TheOfflineSwitchHoldsAtTheGateway(unittest.TestCase):
open_retrying."""
held = tests.scratch_dir(self) / "held.txt"
held.write_bytes(b"local")
self.assertEqual(upstream.fetch_body(held.as_uri()), b"local")
self.assertEqual(forgehttp.fetch_body(held.as_uri()), b"local")
def test_the_cache_answers_as_an_offline_run(self):
cache = str(tests.scratch_dir(self))
with mock.patch.object(upstream, "http_json", side_effect=_no_network), \
mock.patch.object(upstream, "http_text", side_effect=_no_network):
with mock.patch.object(forgehttp, "http_json", side_effect=_no_network), \
mock.patch.object(forgehttp, "http_text", side_effect=_no_network):
self.assertIsNone(upstream.cached_api("https://api.github.com/x", cache, False))
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.fetch_file(parse_repo("https://github.com/o/n"), "abc", "a.c", cache)
@@ -531,12 +533,12 @@ class TestCache(unittest.TestCase):
self.dir = self.tmp.name
self.repo = parse_repo("https://github.com/o/n")
self.calls: list[str] = []
self._orig = (upstream.http_text, upstream.http_json)
upstream.http_text = self._fake
upstream.http_json = _no_network
self._orig = (forgehttp.http_text, forgehttp.http_json)
forgehttp.http_text = self._fake
forgehttp.http_json = _no_network
def tearDown(self):
upstream.http_text, upstream.http_json = self._orig
forgehttp.http_text, forgehttp.http_json = self._orig
self.tmp.cleanup()
def _fake(self, url: str) -> str | None:
@@ -562,7 +564,7 @@ class TestCache(unittest.TestCase):
def test_offline_miss_is_not_absence(self):
# Returning None made profile_sync report an existing file as GONE.
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.fetch_file(self.repo, "abc", "a.c", self.dir, offline=True)
self.assertEqual(self.calls, [])
@@ -585,7 +587,7 @@ class TestCache(unittest.TestCase):
self.assertEqual(self.calls, [])
def test_missing_file_is_cached_as_absent(self):
upstream.http_text = lambda url: None
forgehttp.http_text = lambda url: None
self.assertIsNone(upstream.fetch_file(self.repo, "abc", "gone.c", self.dir))
self.assertIsNone(
upstream.fetch_file(self.repo, "abc", "gone.c", self.dir, offline=True)
@@ -618,12 +620,12 @@ class TestRevisions(unittest.TestCase):
self.repo = parse_repo("https://github.com/o/n")
self.responses: dict[str, object] = {}
self.calls: list[str] = []
self._orig = (upstream.http_json, upstream.http_text)
upstream.http_json = self._fake
upstream.http_text = _no_network
self._orig = (forgehttp.http_json, forgehttp.http_text)
forgehttp.http_json = self._fake
forgehttp.http_text = _no_network
def tearDown(self):
upstream.http_json, upstream.http_text = self._orig
forgehttp.http_json, forgehttp.http_text = self._orig
self.tmp.cleanup()
def _fake(self, url: str):
@@ -645,7 +647,7 @@ class TestRevisions(unittest.TestCase):
self.assertEqual(len(self.calls), 2)
self.assertIn("sha=main", self.calls[0])
self.assertEqual(os.listdir(self.dir), [])
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.resolve_head(self.repo, None, offline=True)
def test_resolve_head_gitlab_uses_id(self):
@@ -663,9 +665,9 @@ class TestRevisions(unittest.TestCase):
def test_an_uncached_tip_offline_is_unknown_not_absent(self):
"""xenios-jp/XeniOS was dropped offline, its preview tip never
cached, and its citations were judged against the other repository."""
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.resolve_head(self.repo, self.dir, offline=True, branch="preview")
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.resolve_commit_at(self.repo, "2026-03-29", self.dir, offline=True)
self.assertEqual(self.calls, [])
@@ -756,10 +758,10 @@ class TestRevisions(unittest.TestCase):
def test_rate_limit_propagates(self):
def boom(url: str):
raise upstream.RateLimitError("quota")
raise forgehttp.RateLimitError("quota")
upstream.http_json = boom
with self.assertRaises(upstream.RateLimitError):
forgehttp.http_json = boom
with self.assertRaises(forgehttp.RateLimitError):
upstream.resolve_head(self.repo, self.dir)
@@ -770,12 +772,12 @@ class TestCompare(unittest.TestCase):
self.dir = self.tmp.name
self.repo = parse_repo("https://github.com/o/n")
self.payload: object = None
self._orig = (upstream.http_json, upstream.http_text)
upstream.http_json = lambda url: self.payload
upstream.http_text = _no_network
self._orig = (forgehttp.http_json, forgehttp.http_text)
forgehttp.http_json = lambda url: self.payload
forgehttp.http_text = _no_network
def tearDown(self):
upstream.http_json, upstream.http_text = self._orig
forgehttp.http_json, forgehttp.http_text = self._orig
self.tmp.cleanup()
def test_list_directory_reads_one_tree(self):
@@ -792,21 +794,21 @@ class TestCompare(unittest.TestCase):
],
}
upstream.http_json = answer
forgehttp.http_json = answer
self.assertEqual(
upstream.list_directory(self.repo, "abc", "hash/", self.dir), ["a.xml", "b.xml"]
upstreamtree.list_directory(self.repo, "abc", "hash/", self.dir), ["a.xml", "b.xml"]
)
self.assertTrue(seen[0].endswith("/repos/o/n/git/trees/abc:hash"))
# Cached: offline, the same answer without a request.
self.assertEqual(
upstream.list_directory(self.repo, "abc", "hash", self.dir, offline=True),
upstreamtree.list_directory(self.repo, "abc", "hash", self.dir, offline=True),
["a.xml", "b.xml"],
)
self.assertEqual(len(seen), 1)
upstream.http_json = lambda url: {"truncated": True, "tree": []}
self.assertIsNone(upstream.list_directory(self.repo, "def", "hash", self.dir))
forgehttp.http_json = lambda url: {"truncated": True, "tree": []}
self.assertIsNone(upstreamtree.list_directory(self.repo, "def", "hash", self.dir))
gitlab = parse_repo("https://gitlab.com/o/n")
self.assertIsNone(upstream.list_directory(gitlab, "abc", "hash", self.dir))
self.assertIsNone(upstreamtree.list_directory(gitlab, "abc", "hash", self.dir))
def test_renamed_file_carries_previous_path(self):
self.payload = {
@@ -819,14 +821,14 @@ class TestCompare(unittest.TestCase):
{"status": "modified", "filename": "a.c"},
]
}
result = upstream.compare(self.repo, "a", "b", self.dir)
result = upstreamtree.compare(self.repo, "a", "b", self.dir)
self.assertFalse(result.truncated)
self.assertEqual(upstream.find_renamed(result, "old.cpp"), "src/new.cpp")
self.assertEqual(upstreamtree.find_renamed(result, "old.cpp"), "src/new.cpp")
def test_no_rename_returns_none(self):
self.payload = {"files": [{"status": "modified", "filename": "a.c"}]}
result = upstream.compare(self.repo, "a", "b", self.dir)
self.assertIsNone(upstream.find_renamed(result, "old.cpp"))
result = upstreamtree.compare(self.repo, "a", "b", self.dir)
self.assertIsNone(upstreamtree.find_renamed(result, "old.cpp"))
def test_truncated_at_github_cap(self):
self.payload = {
@@ -834,11 +836,11 @@ class TestCompare(unittest.TestCase):
{"status": "modified", "filename": f"f{i}.c"} for i in range(300)
]
}
self.assertTrue(upstream.compare(self.repo, "a", "b", self.dir).truncated)
self.assertTrue(upstreamtree.compare(self.repo, "a", "b", self.dir).truncated)
def test_missing_comparison_is_empty_and_truncated(self):
self.payload = None
result = upstream.compare(self.repo, "a", "b", self.dir)
result = upstreamtree.compare(self.repo, "a", "b", self.dir)
self.assertEqual(result.files, [])
self.assertTrue(result.truncated)
@@ -855,8 +857,8 @@ class TestCompare(unittest.TestCase):
}
]
}
result = upstream.compare(repo, "a", "b", self.dir)
self.assertEqual(upstream.find_renamed(result, "old.c"), "new.c")
result = upstreamtree.compare(repo, "a", "b", self.dir)
self.assertEqual(upstreamtree.find_renamed(result, "old.c"), "new.c")
def test_commits_touching_counts_the_commits_after_the_pin(self):
"""Listing from the pin counted its history: freeintv's pin on HEAD
@@ -874,7 +876,7 @@ class TestCompare(unittest.TestCase):
return value
return listing
upstream.http_json = answer
forgehttp.http_json = answer
self.assertEqual(
upstream.commits_touching(self.repo, "a.c", "base", self.dir, head="tip"), 2
)
@@ -899,7 +901,7 @@ class TestCompare(unittest.TestCase):
return value
return list(listing)
upstream.http_json = answer
forgehttp.http_json = answer
self.assertEqual(upstream.commits_touching(self.repo, "a.c", "base", self.dir), 1)
for cached in (Path(self.dir) / "_api").glob("*.json"):
stale = _os.path.getmtime(cached) - upstream.MOVING_TTL - 1
@@ -918,7 +920,7 @@ class TestCompare(unittest.TestCase):
def answer(url):
return answers[-1]
upstream.http_json = answer
forgehttp.http_json = answer
self.assertIsNone(upstream.tag_commit(self.repo, "v2.0", self.dir))
for cached in (Path(self.dir) / "_api").glob("*.json"):
stale = _os.path.getmtime(cached) - upstream.MOVING_TTL - 1
@@ -939,19 +941,19 @@ class TestGitlabTree(unittest.TestCase):
self.dir = self.tmp.name
self.repo = upstream.parse_repo("https://gitlab.com/g/p")
self.pages: dict[int, object] = {}
self._orig = (upstream.http_json, upstream.http_text)
self._orig = (forgehttp.http_json, forgehttp.http_text)
def fake(url):
page = int(url.rsplit("page=", 1)[1])
payload = self.pages.get(page)
if payload == "boom":
raise upstream.UpstreamError(url)
raise forgehttp.UpstreamError(url)
return payload
upstream.http_json = fake
forgehttp.http_json = fake
def tearDown(self):
upstream.http_json, upstream.http_text = self._orig
forgehttp.http_json, forgehttp.http_text = self._orig
self.tmp.cleanup()
def _blobs(self, *names):
@@ -961,41 +963,41 @@ class TestGitlabTree(unittest.TestCase):
self.pages[1] = self._blobs("src/a.c", "src/b.c") + [
{"type": "tree", "path": "src"}
]
paths, truncated = upstream.list_tree(self.repo, "sha", self.dir)
paths, truncated = upstreamtree.list_tree(self.repo, "sha", self.dir)
self.assertEqual(paths, ["src/a.c", "src/b.c"])
self.assertFalse(truncated)
def test_pages_accumulate_until_a_short_one(self):
self.pages[1] = self._blobs(
*[f"f{i}.c" for i in range(upstream.TREE_PAGE_SIZE)]
*[f"f{i}.c" for i in range(upstreamtree.TREE_PAGE_SIZE)]
)
self.pages[2] = self._blobs("last.c")
paths, truncated = upstream.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstream.TREE_PAGE_SIZE + 1)
paths, truncated = upstreamtree.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstreamtree.TREE_PAGE_SIZE + 1)
self.assertIn("last.c", paths)
self.assertFalse(truncated)
def test_unreadable_page_reports_truncation(self):
self.pages[1] = self._blobs(
*[f"f{i}.c" for i in range(upstream.TREE_PAGE_SIZE)]
*[f"f{i}.c" for i in range(upstreamtree.TREE_PAGE_SIZE)]
)
self.pages[2] = None
paths, truncated = upstream.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstream.TREE_PAGE_SIZE)
paths, truncated = upstreamtree.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstreamtree.TREE_PAGE_SIZE)
self.assertTrue(truncated)
def test_gitlinks_of_a_truncated_listing_raise(self):
"""A lost page read as "no submodule there"."""
self.pages[1] = [{"type": "commit", "path": "core", "id": "c" * 40}] + self._blobs(
*[f"f{i}.c" for i in range(upstream.TREE_PAGE_SIZE - 1)]
*[f"f{i}.c" for i in range(upstreamtree.TREE_PAGE_SIZE - 1)]
)
self.pages[2] = None
with self.assertRaises(upstream.TruncatedListingError):
upstream.list_gitlinks(self.repo, "sha", self.dir)
with self.assertRaises(forgehttp.TruncatedListingError):
upstreamtree.list_gitlinks(self.repo, "sha", self.dir)
def test_gitlinks_of_a_whole_listing(self):
self.pages[1] = [{"type": "commit", "path": "core", "id": "c" * 40}]
self.assertEqual(upstream.list_gitlinks(self.repo, "sha", self.dir), {"core": "c" * 40})
self.assertEqual(upstreamtree.list_gitlinks(self.repo, "sha", self.dir), {"core": "c" * 40})
@tests.ONLINE
@@ -1016,7 +1018,7 @@ class TestGiteaCommitAt(unittest.TestCase):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.urls: list[str] = []
original = upstream.http_json
original = forgehttp.http_json
def fake(url):
self.urls.append(url)
@@ -1024,8 +1026,8 @@ class TestGiteaCommitAt(unittest.TestCase):
page = int(url.rsplit("page=", 1)[1])
return self.PAGES.get(page, [])
upstream.http_json = fake
self.addCleanup(setattr, upstream, "http_json", original)
forgehttp.http_json = fake
self.addCleanup(setattr, forgehttp, "http_json", original)
def test_the_first_commit_by_the_cutoff(self):
repo = parse_repo("https://codeberg.org/iyzsong/gam4980")
@@ -1055,7 +1057,7 @@ class TestCurrentSlug(unittest.TestCase):
},
}
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(upstream, "http_json", side_effect=answers.get):
mock.patch.object(forgehttp, "http_json", side_effect=answers.get):
github = parse_repo("https://github.com/AloysHF/NicaiEmu")
gitlab = parse_repo("https://gitlab.com/g/sub/p")
self.assertEqual(upstream.current_slug(github, tmp), "AloysHF/CoolbarEmu")
@@ -1095,10 +1097,10 @@ class TestNewestTag(unittest.TestCase):
class TestNamedTagCommit(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream.http_json
self.saved = forgehttp.http_json
def tearDown(self):
upstream.http_json = self.saved
forgehttp.http_json = self.saved
self.tmp.cleanup()
def test_gitlab_tag_is_asked_by_name(self):
@@ -1108,7 +1110,7 @@ class TestNamedTagCommit(unittest.TestCase):
asked.append(url)
return {"name": "1.2.35", "commit": {"id": "c74fc36"}}
upstream.http_json = answer
forgehttp.http_json = answer
repo = parse_repo("https://gitlab.com/jengun/sdltrs")
self.assertEqual(upstream.tag_commit(repo, "1.2.35", self.tmp.name), "c74fc36")
self.assertTrue(asked[0].endswith("/repository/tags/1.2.35"))
@@ -1118,10 +1120,10 @@ class TestNamedTagCommit(unittest.TestCase):
class TestForkBase(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream.http_json
self.saved = forgehttp.http_json
def tearDown(self):
upstream.http_json = self.saved
forgehttp.http_json = self.saved
self.tmp.cleanup()
def test_the_merge_base_github_names(self):
@@ -1131,15 +1133,15 @@ class TestForkBase(unittest.TestCase):
asked.append(url)
return {"merge_base_commit": {"sha": "base"}, "status": "diverged"}
upstream.http_json = answer
forgehttp.http_json = answer
up, fork = make_repo("github.com", "o", "up"), make_repo("github.com", "f", "port")
self.assertEqual(upstream.fork_base(up, "tip", fork, "head", self.tmp.name), "base")
self.assertEqual(upstreamtree.fork_base(up, "tip", fork, "head", self.tmp.name), "base")
self.assertTrue(asked[0].endswith("/repos/o/up/compare/tip...f:port:head"))
def test_no_network_is_none(self):
upstream.http_json = lambda url: None
forgehttp.http_json = lambda url: None
up, fork = make_repo("github.com", "o", "up"), make_repo("github.com", "f", "port")
self.assertIsNone(upstream.fork_base(up, "tip", fork, "head", self.tmp.name))
self.assertIsNone(upstreamtree.fork_base(up, "tip", fork, "head", self.tmp.name))
def _tarball(files: dict[str, str]) -> bytes:
@@ -1173,43 +1175,43 @@ class TestGitlabDirectoryArchive(unittest.TestCase):
def test_files_land_in_the_cache_fetch_file_reads(self):
calls = []
with mock.patch.object(upstream, "fetch_body", side_effect=lambda url: calls.append(url) or self.body):
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(forgehttp, "fetch_body", side_effect=lambda url: calls.append(url) or self.body):
held = upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
self.assertEqual(held, {"sys/a/system.ini", "sys/b/system.ini"})
self.assertEqual(len(calls), 1)
self.assertIn("archive.tar.gz?sha=abc&path=sys", calls[0])
with mock.patch.object(upstream, "http_text", side_effect=_no_network):
with mock.patch.object(forgehttp, "http_text", side_effect=_no_network):
lines = upstream.fetch_file(self.repo, "abc", "sys/b/system.ini", self.tmp.name, offline=True)
self.assertEqual(lines, ["[core.x]"])
def test_a_second_run_reads_the_index_offline(self):
with mock.patch.object(upstream, "fetch_body", return_value=self.body):
upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True)
with mock.patch.object(forgehttp, "fetch_body", return_value=self.body):
upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(forgehttp, "fetch_body", side_effect=_no_network):
held = upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True)
self.assertEqual(held, {"sys/a/system.ini", "sys/b/system.ini"})
def test_offline_without_index_knows_nothing(self):
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True))
with mock.patch.object(forgehttp, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True))
def test_other_forges_are_left_to_per_file_reads(self):
github = parse_repo("https://github.com/o/r")
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstream.cache_gitlab_directory(github, "abc", "sys", self.tmp.name))
with mock.patch.object(forgehttp, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstreamtree.cache_gitlab_directory(github, "abc", "sys", self.tmp.name))
def test_a_refused_api_falls_back_to_git(self):
refused = upstream.RateLimitError("429", "gitlab.com")
with mock.patch.object(upstream, "fetch_body", side_effect=refused), \
mock.patch.object(upstream, "_sparse_git_files", return_value={"sys/a/system.ini": "x"}) as git:
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
refused = forgehttp.RateLimitError("429", "gitlab.com")
with mock.patch.object(forgehttp, "fetch_body", side_effect=refused), \
mock.patch.object(upstreamtree, "_sparse_git_files", return_value={"sys/a/system.ini": "x"}) as git:
held = upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
self.assertEqual(held, {"sys/a/system.ini"})
git.assert_called_once()
def test_an_empty_archive_is_an_error_not_an_empty_directory(self):
with mock.patch.object(upstream, "fetch_body", return_value=_tarball({"p/other/x": "y"})), \
self.assertRaises(upstream.UpstreamError):
upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(forgehttp, "fetch_body", return_value=_tarball({"p/other/x": "y"})), \
self.assertRaises(forgehttp.UpstreamError):
upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
if __name__ == "__main__":
+3 -2
View File
@@ -27,6 +27,7 @@ import profile_sync
from profiling import resolver
from profiling import yamledit
from core import upstream
from core import upstreamtree
from profiling import versionbasis
from model.profilerepos import pin_field
from model.profiles import load_emulator_profiles
@@ -293,7 +294,7 @@ class TheVersionRepositoryIsTheBasisRepository(unittest.TestCase):
with mock.patch.object(upstream, "latest_release", return_value=None), \
mock.patch.object(upstream, "newest_tag", return_value=None), \
mock.patch.object(upstream, "tag_commit", side_effect=tag_commit), \
mock.patch.object(upstream, "ancestry", return_value=(3, 0)) as ancestry:
mock.patch.object(upstreamtree, "ancestry", return_value=(3, 0)) as ancestry:
profiling_run._attach_version(args, dict(self.PROFILE, core_version="v1"), report)
self.assertEqual(set(asked), {"o/up"})
self.assertEqual(report.version.tag_commit, "uptag")
@@ -334,7 +335,7 @@ class TheTagCoreVersionNames(unittest.TestCase):
return_value=upstream.Release("2.10.0", "2026-11-01", False)), \
mock.patch.object(upstream, "newest_tag", return_value="2.10.0"), \
mock.patch.object(upstream, "tag_commit", side_effect=tag_commit), \
mock.patch.object(upstream, "ancestry", side_effect=ancestry):
mock.patch.object(upstreamtree, "ancestry", side_effect=ancestry):
profiling_run._attach_version(args, profile, report)
return report, asked
+4 -3
View File
@@ -680,9 +680,10 @@ under `.cache/upstream/`, addressed by commit sha, so `--offline` replays a
previous run. GitHub, GitLab and Forgejo upstreams are supported, other
hosts are reported as skipped.
The forge side lives in `core/upstream.py`: it resolves a revision, fetches a
file at a given sha, and compares trees, for the forge families the
profiles point at. It knows nothing about profile structure, so anchoring
The forge side lives in `core/upstream.py`, which resolves a revision and
fetches a file at a given sha, `core/upstreamtree.py`, which compares two
revisions and lists trees, and `core/forgehttp.py`, which sends the requests,
for the forge families the profiles point at. It knows nothing about profile structure, so anchoring
logic and repository access stay testable apart.
### resolve/validation.py