readthrough 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. readthrough/__init__.py +8 -0
  2. readthrough/__main__.py +3 -0
  3. readthrough/agents.py +344 -0
  4. readthrough/analyze.py +537 -0
  5. readthrough/assets/SKILL.md +86 -0
  6. readthrough/assets/defaults.toml +143 -0
  7. readthrough/assets/profile-reference.md +133 -0
  8. readthrough/assets/vendor/README.md +22 -0
  9. readthrough/assets/vendor/cose-base.js +3214 -0
  10. readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
  11. readthrough/assets/vendor/cytoscape.min.js +31 -0
  12. readthrough/assets/vendor/layout-base.js +5230 -0
  13. readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
  14. readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
  15. readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
  16. readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
  17. readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
  18. readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
  19. readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
  20. readthrough/assets/vendor/lucide-icons.js +36 -0
  21. readthrough/assets/vendor/marked.umd.js +82 -0
  22. readthrough/assets/vendor/purify.min.js +7 -0
  23. readthrough/assets/web/dashboard.css +202 -0
  24. readthrough/assets/web/dashboard.html +48 -0
  25. readthrough/assets/web/dashboard.js +937 -0
  26. readthrough/assets/web/setup.css +57 -0
  27. readthrough/assets/web/setup.html +28 -0
  28. readthrough/assets/web/setup.js +342 -0
  29. readthrough/assets/web/theme.css +36 -0
  30. readthrough/assistants.py +699 -0
  31. readthrough/brief.py +145 -0
  32. readthrough/build.py +616 -0
  33. readthrough/ci.py +107 -0
  34. readthrough/cli.py +958 -0
  35. readthrough/config.py +533 -0
  36. readthrough/contract.py +394 -0
  37. readthrough/engine.py +230 -0
  38. readthrough/faults.py +92 -0
  39. readthrough/files.py +110 -0
  40. readthrough/forges/__init__.py +614 -0
  41. readthrough/forges/azure_devops.py +658 -0
  42. readthrough/forges/forgejo.py +300 -0
  43. readthrough/forges/github.py +487 -0
  44. readthrough/forges/gitlab.py +335 -0
  45. readthrough/ledger.py +61 -0
  46. readthrough/limits.py +26 -0
  47. readthrough/logs.py +169 -0
  48. readthrough/membership.py +76 -0
  49. readthrough/model.py +177 -0
  50. readthrough/onboard.py +551 -0
  51. readthrough/onboard_model.py +319 -0
  52. readthrough/process.py +169 -0
  53. readthrough/profile.py +699 -0
  54. readthrough/py.typed +0 -0
  55. readthrough/registry.py +157 -0
  56. readthrough/review.py +394 -0
  57. readthrough/rules.py +111 -0
  58. readthrough/runtimes/__init__.py +297 -0
  59. readthrough/runtimes/anthropic.py +278 -0
  60. readthrough/runtimes/copilot.py +313 -0
  61. readthrough/runtimes/openai.py +307 -0
  62. readthrough/serve.py +817 -0
  63. readthrough/study.py +327 -0
  64. readthrough/system.py +205 -0
  65. readthrough/terminals.py +168 -0
  66. readthrough/tuning.py +266 -0
  67. readthrough/usage.py +169 -0
  68. readthrough/web_setup.py +635 -0
  69. readthrough-0.4.0.dist-info/METADATA +123 -0
  70. readthrough-0.4.0.dist-info/RECORD +73 -0
  71. readthrough-0.4.0.dist-info/WHEEL +4 -0
  72. readthrough-0.4.0.dist-info/entry_points.txt +2 -0
  73. readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,614 @@
1
+ """Forges: where pull requests come from. One adapter per platform, chosen per repo with ``forge = "..."``.
2
+
3
+ Every adapter produces the records in ``model.py`` and nothing else reads a platform's API. What an
4
+ adapter can't supply (a forge without review decisions, a diff endpoint, or required checks) it marks as
5
+ unsupported, and the build says so rather than reading silence as "none".
6
+
7
+ Two transports. GitHub keeps the ``gh`` CLI, which carries your sign-in, SSO, and proxies. The others
8
+ speak REST through ``urllib`` with a token from the platform's own CLI when it's installed and signed in
9
+ (``glab``, ``az``), else from an environment variable, else anonymously, which is enough for public repos.
10
+ Credentials never live in ``config.toml``; the ``[forges.<name>]`` tables hold hosts and variable names.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import difflib
16
+ import json
17
+ import logging
18
+ import os
19
+ import random
20
+ import re
21
+ import threading
22
+ import time
23
+ import urllib.error
24
+ import urllib.parse
25
+ import urllib.request
26
+ from collections.abc import Callable
27
+ from dataclasses import dataclass
28
+ from http import HTTPStatus
29
+ from pathlib import Path
30
+ from typing import Any, ClassVar
31
+
32
+ from readthrough import __version__
33
+ from readthrough.faults import AuthError, ForgeError, NetworkError, RateLimited, Timeout, TooLarge, classify_http
34
+ from readthrough.logs import pool_map
35
+ from readthrough.model import PATH_SEGMENT, Capability, MergedPullRequest, PullRequest
36
+ from readthrough.process import Secret, redact, remember
37
+ from readthrough.registry import Registry
38
+ from readthrough.tuning import ForgeTuning, default_tuning
39
+
40
+ log = logging.getLogger(__name__)
41
+
42
+ # ---------------------------------------------------------------- retries, shared by every transport
43
+
44
+
45
+ class _Slots:
46
+ """One limit on concurrent forge calls for the whole process, sized by the first caller."""
47
+
48
+ def __init__(self) -> None:
49
+ self._lock = threading.Lock()
50
+ self._semaphore: threading.BoundedSemaphore | None = None
51
+
52
+ def get(self, concurrency: int) -> threading.BoundedSemaphore:
53
+ with self._lock:
54
+ if self._semaphore is None:
55
+ self._semaphore = threading.BoundedSemaphore(concurrency)
56
+ return self._semaphore
57
+
58
+
59
+ _slots = _Slots()
60
+
61
+ # Jitter keeps retries from different repos from lining up. Its own generator, so seeding it (tests) or
62
+ # anything else using `random` can't change the other's sequence.
63
+ JITTER_MAX = 0.25
64
+ jitter = random.Random() # noqa: S311 - timing jitter, not security
65
+
66
+
67
+ def backoff(attempt: int, tuning: ForgeTuning, exc: ForgeError, rng: random.Random | None = None) -> float:
68
+ """Seconds to wait before retry ``attempt``: exponential with a cap, plus up to ``JITTER_MAX`` of itself.
69
+
70
+ A rate limit waits the configured time, or what the forge asked for in ``Retry-After`` when that's
71
+ shorter (GitLab says exactly when the window resets); either way, never more than the configured wait.
72
+ """
73
+ if isinstance(exc, RateLimited):
74
+ asked = exc.retry_after
75
+ return min(tuning.rate_limit_wait_seconds, asked) if asked else tuning.rate_limit_wait_seconds
76
+ base = min(tuning.retry_max_backoff_seconds, tuning.retry_backoff_seconds * 2 ** (attempt - 1))
77
+ return base * (1 + (rng or jitter).uniform(0, JITTER_MAX))
78
+
79
+
80
+ # ---------------------------------------------------------------- credentials
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class Credential:
85
+ """How a forge is authenticated: where the token came from, and the token. ``source`` is safe to log."""
86
+
87
+ source: str # "env GITLAB_TOKEN" | "glab" | "az" | "anonymous"
88
+ token: Secret | None = None
89
+ scheme: str = "Bearer" # the Authorization scheme: Bearer, token, or Basic (ADO PATs)
90
+
91
+ def header(self) -> str | None:
92
+ if self.token is None:
93
+ return None
94
+ value = self.token.reveal()
95
+ if self.scheme == "Basic":
96
+ import base64
97
+
98
+ value = base64.b64encode(f":{value}".encode()).decode()
99
+ return f"{self.scheme} {value}"
100
+
101
+
102
+ _TOKEN_RE = re.compile(r"^[\x21-\x7e]{8,4096}$") # one line of printable ASCII: what every forge's tokens are
103
+
104
+
105
+ def credential(*, env: str, cli: Callable[[], str | None] | None, cli_name: str, scheme: str = "Bearer") -> Credential:
106
+ """An explicit variable wins, then the platform's CLI if it's signed in, else anonymous.
107
+
108
+ Whatever a CLI prints is only a token if it looks like one. A CLI that answers with a banner or an error
109
+ on stdout (a wrapper, a stand-in, a prompt to sign in) would otherwise become an Authorization header,
110
+ and urllib refuses header values with newlines by crashing the call rather than failing it.
111
+ """
112
+ value = os.environ.get(env, "").strip() if env else ""
113
+ if value:
114
+ if not _TOKEN_RE.match(value):
115
+ log.warning("%s is set but doesn't look like a token; calling anonymously", env)
116
+ else:
117
+ return Credential(f"env {env}", remember(Secret(value)), scheme)
118
+ if cli is not None:
119
+ found = (cli() or "").strip()
120
+ if found and _TOKEN_RE.match(found):
121
+ return Credential(cli_name, remember(Secret(found)), scheme)
122
+ if found:
123
+ log.warning("%s printed something that isn't a token; calling anonymously", cli_name)
124
+ return Credential("anonymous", None, scheme)
125
+
126
+
127
+ _cli_tokens: dict[str, tuple[str | None, float]] = {}
128
+ _cli_tokens_lock = threading.Lock()
129
+ RETRY_MISSING_TOKEN_SECONDS = 600.0
130
+
131
+
132
+ def cached_cli_token(key: str, lookup: Callable[[], str | None]) -> str | None:
133
+ """Ask a CLI for a token once per process. Spawning ``az`` or ``glab`` costs seconds; the answer doesn't change.
134
+
135
+ Except from "none": someone who signs in after seeing `doctor`'s advice shouldn't have to restart the
136
+ server, so a lookup that found nothing is asked again after a while.
137
+ """
138
+ with _cli_tokens_lock:
139
+ found = _cli_tokens.get(key)
140
+ if found is None or (found[0] is None and time.monotonic() - found[1] > RETRY_MISSING_TOKEN_SECONDS):
141
+ found = _cli_tokens[key] = (lookup(), time.monotonic())
142
+ return found[0]
143
+
144
+
145
+ # ---------------------------------------------------------------- REST over urllib
146
+
147
+
148
+ @dataclass(frozen=True)
149
+ class Response:
150
+ status: int
151
+ headers: dict[str, str] # lower-cased names
152
+ text: str
153
+ body: bytes = b"" # the raw bytes, for blobs; recorded responses carry only text
154
+
155
+ def json(self) -> Any:
156
+ return json.loads(self.text) if self.text.strip() else None
157
+
158
+ @property
159
+ def content(self) -> bytes:
160
+ return self.body or self.text.encode("utf-8")
161
+
162
+
163
+ class Rest:
164
+ """HTTP for one API base: a timeout on every call, UTF-8, errors classified by status.
165
+
166
+ ``cred`` may be a callable that finds the credential; it's called on the first request (or when something
167
+ asks ``describe_auth``), so building an adapter for a URL or a session id never spawns a CLI.
168
+ """
169
+
170
+ def __init__(
171
+ self, base: str, cred: Credential | Callable[[], Credential], tuning: ForgeTuning, *,
172
+ headers: dict[str, str] | None = None,
173
+ ) -> None: # fmt: skip
174
+ self.base = base.rstrip("/") + "/"
175
+ self._cred: Credential | None = cred if isinstance(cred, Credential) else None
176
+ self._find_cred = None if isinstance(cred, Credential) else cred
177
+ self._cred_lock = threading.Lock()
178
+ self.tuning = tuning
179
+ self.headers = {"User-Agent": f"readthrough/{__version__}", "Accept": "application/json", **(headers or {})}
180
+
181
+ @property
182
+ def cred(self) -> Credential:
183
+ with self._cred_lock:
184
+ if self._cred is None:
185
+ self._cred = self._find_cred() if self._find_cred else Credential("anonymous")
186
+ return self._cred
187
+
188
+ def url(self, path: str, params: dict[str, Any] | None = None) -> str:
189
+ url = path if path.startswith("http") else self.base + path.lstrip("/")
190
+ if params:
191
+ query = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None}, doseq=True)
192
+ url += ("&" if "?" in url else "?") + query
193
+ return url
194
+
195
+ def call(
196
+ self, method: str, path: str, *, params: dict[str, Any] | None = None, body: Any = None,
197
+ headers: dict[str, str] | None = None, absent: tuple[type[ForgeError], ...] = (),
198
+ ) -> Response | None: # fmt: skip
199
+ """One request. Raises a classified error for any status >= 400, except those in ``absent`` (-> None)."""
200
+ url = self.url(path, params)
201
+ what = f"{method} {urllib.parse.urlsplit(url).path}"
202
+ data = json.dumps(body).encode() if body is not None else None
203
+ req = urllib.request.Request(url, data=data, method=method, headers={**self.headers, **(headers or {})}) # noqa: S310 - https API URLs only
204
+ if data is not None:
205
+ req.add_header("Content-Type", "application/json")
206
+ auth = self.cred.header()
207
+ if auth and urllib.parse.urlsplit(url).netloc == urllib.parse.urlsplit(self.base).netloc:
208
+ # Only to our own host, and unredirected: urllib copies ordinary headers onto a redirect, and a
209
+ # forge that bounces raw content to object storage must not get the token with it.
210
+ req.add_unredirected_header("Authorization", auth)
211
+ started = time.monotonic()
212
+ try:
213
+ with urllib.request.urlopen(req, timeout=self.tuning.timeout_seconds) as resp: # noqa: S310 - https API URLs
214
+ raw = resp.read()
215
+ text = raw.decode("utf-8", errors="replace")
216
+ status, resp_headers = resp.status, {k.lower(): v for k, v in resp.headers.items()}
217
+ except urllib.error.HTTPError as exc:
218
+ text = redact(exc.read().decode("utf-8", errors="replace"))
219
+ cls = classify_http(exc.code, text)
220
+ if absent and issubclass(cls, absent):
221
+ return None
222
+ first = error_summary(text)
223
+ error = cls(
224
+ f"{what} failed: HTTP {exc.code} {first}".rstrip(), what=what,
225
+ stderr=f"HTTP {exc.code} {first}\n{text[:4000]}".rstrip(),
226
+ headers={k.lower(): v for k, v in exc.headers.items()},
227
+ ) # fmt: skip
228
+ if isinstance(error, RateLimited):
229
+ error.retry_after = retry_after(exc.headers.get("Retry-After"), exc.headers.get("RateLimit-Reset"))
230
+ raise error from exc
231
+ except TimeoutError as exc:
232
+ raise Timeout(f"{what} timed out after {self.tuning.timeout_seconds:.0f}s", what=what) from exc
233
+ except urllib.error.URLError as exc:
234
+ raise NetworkError(f"{what} failed: {exc.reason}", what=what, stderr=str(exc.reason)) from exc
235
+ log.debug("%s: %d in %.2fs", what, status, time.monotonic() - started)
236
+ if status == HTTPStatus.NON_AUTHORITATIVE_INFORMATION and "text/html" in resp_headers.get("content-type", ""):
237
+ # Azure DevOps answers an unauthorized API call with its sign-in page and a 203, not a 401.
238
+ if absent and issubclass(AuthError, absent):
239
+ return None
240
+ raise AuthError(
241
+ f"{what} needs sign-in (the forge answered with its sign-in page)",
242
+ what=what,
243
+ stderr="HTTP 203 sign-in page",
244
+ )
245
+ return Response(status, resp_headers, text, raw)
246
+
247
+
248
+ def error_summary(text: str) -> str:
249
+ """One readable line from an error body: the ``message`` of a JSON error (what every forge's API sends),
250
+ else the body's first line. For the one-line ``reason`` a log or `doctor` shows; the body stays in ``stderr``."""
251
+ try:
252
+ data = json.loads(text)
253
+ except ValueError:
254
+ data = None
255
+ if isinstance(data, dict):
256
+ for key in ("message", "error_description", "error"):
257
+ if isinstance(data.get(key), str) and data[key].strip():
258
+ return data[key].strip()[:300]
259
+ return next((line.strip() for line in text.splitlines() if line.strip()), "")[:300]
260
+
261
+
262
+ def retry_after(header: str | None, reset: str | None = None, *, now: float | None = None) -> float | None:
263
+ """Seconds to wait from a ``Retry-After`` (seconds) or ``RateLimit-Reset`` (Unix time) header, if either parses."""
264
+ for value, absolute in ((header, False), (reset, True)):
265
+ if value and value.strip().isdigit():
266
+ seconds = float(value) - (now if now is not None else time.time()) if absolute else float(value)
267
+ return max(0.0, seconds)
268
+ return None
269
+
270
+
271
+ def link_next(headers: dict[str, str]) -> str | None:
272
+ """The ``rel="next"`` URL from a Link header (GitLab, Forgejo, GitHub REST), or None."""
273
+ for part in headers.get("link", "").split(","):
274
+ if 'rel="next"' in part:
275
+ return part.split(";")[0].strip().strip("<>")
276
+ return None
277
+
278
+
279
+ @dataclass(frozen=True)
280
+ class FilePair:
281
+ """Both versions of one changed file, for a forge that serves files but no diff. ``None`` means no such side."""
282
+
283
+ old_path: str | None
284
+ new_path: str | None
285
+ old: bytes | None
286
+ new: bytes | None
287
+
288
+
289
+ def _is_binary(data: bytes) -> bool:
290
+ return b"\0" in data[:8000] # git's own rule: a NUL in the first 8 KB
291
+
292
+
293
+ def assemble_diff(pairs: list[FilePair]) -> str:
294
+ """A unified diff in git's layout from file pairs, for forges with no diff endpoint (Azure DevOps).
295
+
296
+ Each file gets ``diff --git`` and ``---``/``+++`` headers with ``a/``, ``b/`` prefixes (``/dev/null`` for an
297
+ added or deleted side), so everything that reads git's diffs reads this one. Binary files are noted the
298
+ way git notes them. Undecodable bytes are replaced rather than failing the whole diff.
299
+ """
300
+ out: list[str] = []
301
+ for pair in pairs:
302
+ old_path, new_path = pair.old_path or pair.new_path or "?", pair.new_path or pair.old_path or "?"
303
+ old, new = pair.old or b"", pair.new or b""
304
+ out.append(f"diff --git a/{old_path} b/{new_path}")
305
+ if pair.old is None:
306
+ out.append("new file mode 100644")
307
+ elif pair.new is None:
308
+ out.append("deleted file mode 100644")
309
+ elif old_path != new_path:
310
+ out += [f"rename from {old_path}", f"rename to {new_path}"]
311
+ if _is_binary(old) or _is_binary(new):
312
+ out.append(f"Binary files a/{old_path} and b/{new_path} differ")
313
+ continue
314
+ a = old.decode("utf-8", "replace").splitlines(keepends=True)
315
+ b = new.decode("utf-8", "replace").splitlines(keepends=True)
316
+ if a == b:
317
+ continue # a pure rename, or a mode change: nothing to show
318
+ header_a = "/dev/null" if pair.old is None else f"a/{old_path}"
319
+ header_b = "/dev/null" if pair.new is None else f"b/{new_path}"
320
+ for i, line in enumerate(difflib.unified_diff(a, b, header_a, header_b, n=3, lineterm="")):
321
+ if i < 2 or line.startswith("@@"): # the two file headers, then hunk headers; content never starts "@@"
322
+ out.append(line)
323
+ continue
324
+ out.append(line.rstrip("\r\n"))
325
+ if not line.endswith("\n"):
326
+ out.append("\")
327
+ return "\n".join(out) + ("\n" if out else "")
328
+
329
+
330
+ # ---------------------------------------------------------------- the adapter contract
331
+
332
+
333
+ @dataclass(frozen=True)
334
+ class CiContext:
335
+ """What a build learns about the repo's CI before looking at any PR."""
336
+
337
+ required: dict[str, Capability[set[str]]] # per base branch: the check names it needs
338
+ main_failing: Capability[set[str]] # checks failing on the default branch right now
339
+ default_branch: str
340
+
341
+
342
+ class Forge:
343
+ """Base for adapters. Subclasses set the class attributes and implement the fetching methods.
344
+
345
+ ``capabilities`` names what the adapter can do beyond the essentials; the build reads it to decide what to
346
+ attempt and what to report as unsupported: ``diffs``, ``required_checks``, ``default_branch_ci``,
347
+ ``rate_limit``, ``memberships``.
348
+ """
349
+
350
+ name: ClassVar[str] = ""
351
+ label: ClassVar[str] = ""
352
+ config_dir: ClassVar[str] = "" # the platform's conventional dot-directory, e.g. ".github"
353
+ shape: ClassVar[str] = "owner/name" # what a repo locator looks like here, for messages and the setup page
354
+ capabilities: ClassVar[frozenset[str]] = frozenset()
355
+ pr_noun: ClassVar[str] = "pull request"
356
+ files_tab: ClassVar[str] = "/files" # appended to a PR's URL to open its changed files (GitLab: /diffs)
357
+ # For the setup page and `doctor`: how this forge is read and where the credential comes from, in the
358
+ # order tried. ``access`` is one line; ``credentials`` are short phrases.
359
+ access: ClassVar[str] = ""
360
+ credentials: ClassVar[tuple[str, ...]] = ()
361
+
362
+ def __init__(
363
+ self, repo: str, options: Any, tuning: ForgeTuning | None = None, *, account: str | None = None
364
+ ) -> None:
365
+ self.repo = repo
366
+ self.options = options
367
+ self.tuning = tuning or default_tuning().forge
368
+ self.account = account
369
+ self.sleep = time.sleep # replaced in tests
370
+
371
+ # ---- identity
372
+
373
+ @classmethod
374
+ def validate_repo(cls, repo: str) -> str | None:
375
+ """Why ``repo`` isn't a valid locator for this forge, or None when it is."""
376
+ raise NotImplementedError
377
+
378
+ @staticmethod
379
+ def bad_segment(parts: list[str], *, spaces: bool = False) -> str | None:
380
+ """Why one of a locator's segments can't be a directory name under ``repos/``, or None.
381
+
382
+ A locator becomes path segments on disk and in URLs, and a forge the user pointed at (or its operator)
383
+ chooses the ``full_name`` it answers with, so every segment is held to the slug grammar: no separators,
384
+ no ``.`` or ``..``, and spaces only where the forge allows them.
385
+ """
386
+ pattern = PATH_SEGMENT if spaces else r"[\w.-]+"
387
+ for part in parts:
388
+ if not re.fullmatch(pattern, part) or part.strip(".") == "":
389
+ return f"segment {part!r} can't be a path"
390
+ return None
391
+
392
+ @classmethod
393
+ def slug(cls, repo: str) -> str:
394
+ """Path segments for URLs and the data directory: ``<forge>/<repo path>``."""
395
+ return f"{cls.name}/{repo}"
396
+
397
+ @classmethod
398
+ def remote_matches(cls, url: str, repo: str) -> bool:
399
+ """Whether a git remote URL (https or ssh, any host alias) points at ``repo``.
400
+
401
+ Most forges put the repo's path at the end of the URL, with or without ``.git``; a forge whose URLs
402
+ are shaped differently (Azure DevOps) overrides this.
403
+ """
404
+ return re.search(rf"[:/]{re.escape(repo.lower())}(?:\.git)?/?$", url.lower()) is not None
405
+
406
+ def web_url(self) -> str:
407
+ raise NotImplementedError
408
+
409
+ def pr_url(self, number: int) -> str:
410
+ raise NotImplementedError
411
+
412
+ def pr_ref(self, number: int) -> str:
413
+ """The git ref to fetch a PR's head from the remote, e.g. ``pull/12/head``."""
414
+ raise NotImplementedError
415
+
416
+ def file_url(self, path: str, branch: str) -> str:
417
+ raise NotImplementedError
418
+
419
+ def new_file_url(self, path: str, branch: str) -> str | None: # noqa: ARG002 - the default has no such page
420
+ """A page where a maintainer can create ``path`` on ``branch``, for proposing a profile upstream."""
421
+ return None
422
+
423
+ def sign_in_hint(self) -> str:
424
+ """For `doctor`: what to run so this forge lets readthrough in. Adapters that know better override it."""
425
+ return f"give readthrough a token: {self.describe_auth()}"
426
+
427
+ def describe_auth(self) -> str:
428
+ """For `doctor`: how calls are authenticated, never including the token."""
429
+ return "gh" if self.name == "github" else "anonymous"
430
+
431
+ # ---- retrying
432
+
433
+ def retrying(self, what: str, call: Callable[[], Any]) -> Any:
434
+ """Run ``call``, retrying temporary failures with backoff under the process-wide concurrency limit."""
435
+ slots = _slots.get(self.tuning.concurrency)
436
+ attempts = self.tuning.retries + 1
437
+ for attempt in range(1, attempts + 1):
438
+ try:
439
+ with slots:
440
+ return call()
441
+ except ForgeError as exc:
442
+ if not exc.retryable or attempt == attempts:
443
+ if exc.retryable:
444
+ exc.args = (f"{exc.args[0]} (gave up after {attempts} attempts)",)
445
+ raise
446
+ wait = backoff(attempt, self.tuning, exc)
447
+ log.warning("%s: %s (attempt %d of %d, retrying in %.1fs)", what, exc.reason, attempt, attempts, wait,
448
+ extra={"attempt": attempt}) # fmt: skip
449
+ self.sleep(wait)
450
+ raise AssertionError("unreachable")
451
+
452
+ # ---- fetching (implemented by adapters)
453
+
454
+ def repo_info(self) -> dict[str, Any]:
455
+ """``{"full_name", "default_branch", "private", "description"}``; raises when the repo can't be read."""
456
+ raise NotImplementedError
457
+
458
+ def fetch_prs(self, limit: int) -> tuple[str, list[PullRequest], int]:
459
+ """Open PRs, newest activity first, up to ``limit``, with the viewer's login and the total open."""
460
+ raise NotImplementedError
461
+
462
+ def merged_prs(self, count: int) -> tuple[str, list[MergedPullRequest]]:
463
+ """The default branch's name and the ``count`` most recently merged PRs, for onboarding."""
464
+ raise NotImplementedError
465
+
466
+ def tree(self, branch: str) -> tuple[list[str], bool]:
467
+ """File paths in the repo at ``branch``, and whether that's all of them.
468
+
469
+ A forge may stop short (GitHub truncates huge trees; paged forges stop at ``max_tree_files``), in which
470
+ case the second value is False and onboarding says so rather than judging patterns against a partial list.
471
+ """
472
+ raise NotImplementedError
473
+
474
+ def read_file(self, path: str) -> str | None:
475
+ """A file's text at the default branch, or None only when it doesn't exist."""
476
+ raise NotImplementedError
477
+
478
+ def read_files(self, paths: list[str]) -> dict[str, str]:
479
+ """The subset of ``paths`` that exist, with their text. Adapters override when they can batch."""
480
+ return {p: text for p in paths if (text := self.read_file(p)) is not None}
481
+
482
+ def list_dir(self, path: str) -> list[str]:
483
+ """File names directly under ``path`` at the default branch; empty when it doesn't exist."""
484
+ raise NotImplementedError
485
+
486
+ def ci_context(self, bases: set[str]) -> CiContext:
487
+ raise NotImplementedError
488
+
489
+ def is_member(self, group: str, login: str) -> bool:
490
+ """Is ``login`` in ``group`` (an org, or ``org/team``)? Only for adapters with the ``memberships`` capability."""
491
+ raise NotImplementedError
492
+
493
+ def rate_limit(self) -> dict[str, int] | None:
494
+ return None
495
+
496
+ # ---- diffs, cached by head so a refresh only downloads PRs that changed
497
+
498
+ def fetch_diff(self, number: int) -> str:
499
+ """The PR's unified diff. Raises ``TooLarge`` when the forge refuses to serve it."""
500
+ raise NotImplementedError
501
+
502
+ _CACHE_SUFFIXES = (".diff", ".toolarge", ".empty")
503
+
504
+ def diff(self, number: int, head: str, cache: Path) -> tuple[str, bool]:
505
+ """A PR's diff, cached by head SHA. Returns (text, fetched).
506
+
507
+ Failures are never cached. A refusal (too large) is remembered for this head as a ``.toolarge``
508
+ marker, and a legitimately empty diff as ``.empty``, so neither is asked for again until the head
509
+ changes.
510
+ """
511
+ path = cache / f"pr-{number}-{head[:12]}.diff"
512
+ marker, empty = path.with_suffix(".toolarge"), path.with_suffix(".empty")
513
+ if path.exists() and path.stat().st_size:
514
+ return path.read_text(encoding="utf-8"), False
515
+ if empty.exists():
516
+ return "", False
517
+ if marker.exists():
518
+ raise TooLarge(
519
+ f"pr diff #{number}: too large for {self.label} to serve (remembered for this commit)",
520
+ what=f"pr diff #{number}",
521
+ )
522
+ try:
523
+ text = self.fetch_diff(number)
524
+ except TooLarge:
525
+ self._forget_diffs(number, cache)
526
+ marker.write_text("", encoding="utf-8")
527
+ raise
528
+ self._forget_diffs(number, cache)
529
+ (path if text else empty).write_text(text, encoding="utf-8")
530
+ return text, True
531
+
532
+ def diffs(self, prs: list[PullRequest], cache: Path) -> tuple[dict[int, str], dict[int, ForgeError], int]:
533
+ """Diffs for every PR: (texts, failures by PR, how many were downloaded rather than cached)."""
534
+ cache.mkdir(parents=True, exist_ok=True)
535
+
536
+ def one(pr: PullRequest) -> tuple[int, str | None, ForgeError | None, bool]:
537
+ try:
538
+ text, fetched = self.diff(pr.number, pr.head, cache)
539
+ except ForgeError as exc:
540
+ return pr.number, None, exc, False
541
+ return pr.number, text, None, fetched
542
+
543
+ results = pool_map(one, prs, self.tuning.concurrency)
544
+ self._prune_cache(cache, {p.number for p in prs})
545
+ texts = {n: t for n, t, _, _ in results if t is not None}
546
+ failures = {n: e for n, _, e, _ in results if e is not None}
547
+ return texts, failures, sum(1 for *_, fetched in results if fetched)
548
+
549
+ def _prune_cache(self, cache: Path, current: set[int]) -> None:
550
+ """Drop empty .diff files (failures cached by older versions) and old entries of PRs no longer listed."""
551
+ cutoff = time.time() - self.tuning.diff_cache_days * 86400
552
+ for path in self._cache_entries(cache, "*"):
553
+ number = path.name.split("-")[1]
554
+ stale = number.isdigit() and int(number) not in current and path.stat().st_mtime < cutoff
555
+ if stale or (path.suffix == ".diff" and not path.stat().st_size):
556
+ path.unlink(missing_ok=True)
557
+
558
+ @classmethod
559
+ def _forget_diffs(cls, number: int, cache: Path) -> None:
560
+ for old in cls._cache_entries(cache, str(number)):
561
+ old.unlink(missing_ok=True)
562
+
563
+ @classmethod
564
+ def _cache_entries(cls, cache: Path, number: str) -> list[Path]:
565
+ return [p for suffix in cls._CACHE_SUFFIXES for p in cache.glob(f"pr-{number}-*{suffix}")]
566
+
567
+
568
+ # ---------------------------------------------------------------- the registry
569
+
570
+
571
+ FORGES: Registry[type[Forge]] = Registry("forge")
572
+ DEFAULT = "github"
573
+
574
+
575
+ @dataclass(frozen=True)
576
+ class NoForgeOptions:
577
+ pass
578
+
579
+
580
+ def names() -> list[str]:
581
+ return FORGES.names()
582
+
583
+
584
+ def adapter(name: str) -> type[Forge]:
585
+ return FORGES.get(name).impl
586
+
587
+
588
+ def make(cfg: Any) -> Forge:
589
+ """The forge for a repo's config: ``cfg.forge`` names the adapter, ``cfg.forge_options`` its validated options."""
590
+ cls = adapter(cfg.forge)
591
+ options = (getattr(cfg, "forge_options", None) or {}).get(cfg.forge) or FORGES.defaults_for(cfg.forge)
592
+ return cls(cfg.repo, options, cfg.tuning.forge, account=getattr(cfg, "account", None))
593
+
594
+
595
+ def validate_repo(forge: str, repo: str) -> str | None:
596
+ return adapter(forge).validate_repo(repo)
597
+
598
+
599
+ def slug(forge: str, repo: str) -> str:
600
+ return adapter(forge).slug(repo)
601
+
602
+
603
+ def _register_builtin() -> None:
604
+ # Imported here so each adapter module can import this one.
605
+ from readthrough.forges import azure_devops, forgejo, github, gitlab # noqa: F401
606
+
607
+
608
+ _register_builtin()
609
+
610
+ __all__ = [
611
+ "DEFAULT", "FORGES", "JITTER_MAX", "CiContext", "Credential", "Forge", "NoForgeOptions", "Response", "Rest",
612
+ "adapter", "backoff", "cached_cli_token", "credential", "jitter", "link_next", "make", "names", "retry_after", "slug",
613
+ "validate_repo",
614
+ ] # fmt: skip