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.
- readthrough/__init__.py +8 -0
- readthrough/__main__.py +3 -0
- readthrough/agents.py +344 -0
- readthrough/analyze.py +537 -0
- readthrough/assets/SKILL.md +86 -0
- readthrough/assets/defaults.toml +143 -0
- readthrough/assets/profile-reference.md +133 -0
- readthrough/assets/vendor/README.md +22 -0
- readthrough/assets/vendor/cose-base.js +3214 -0
- readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
- readthrough/assets/vendor/cytoscape.min.js +31 -0
- readthrough/assets/vendor/layout-base.js +5230 -0
- readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
- readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
- readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
- readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
- readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
- readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
- readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
- readthrough/assets/vendor/lucide-icons.js +36 -0
- readthrough/assets/vendor/marked.umd.js +82 -0
- readthrough/assets/vendor/purify.min.js +7 -0
- readthrough/assets/web/dashboard.css +202 -0
- readthrough/assets/web/dashboard.html +48 -0
- readthrough/assets/web/dashboard.js +937 -0
- readthrough/assets/web/setup.css +57 -0
- readthrough/assets/web/setup.html +28 -0
- readthrough/assets/web/setup.js +342 -0
- readthrough/assets/web/theme.css +36 -0
- readthrough/assistants.py +699 -0
- readthrough/brief.py +145 -0
- readthrough/build.py +616 -0
- readthrough/ci.py +107 -0
- readthrough/cli.py +958 -0
- readthrough/config.py +533 -0
- readthrough/contract.py +394 -0
- readthrough/engine.py +230 -0
- readthrough/faults.py +92 -0
- readthrough/files.py +110 -0
- readthrough/forges/__init__.py +614 -0
- readthrough/forges/azure_devops.py +658 -0
- readthrough/forges/forgejo.py +300 -0
- readthrough/forges/github.py +487 -0
- readthrough/forges/gitlab.py +335 -0
- readthrough/ledger.py +61 -0
- readthrough/limits.py +26 -0
- readthrough/logs.py +169 -0
- readthrough/membership.py +76 -0
- readthrough/model.py +177 -0
- readthrough/onboard.py +551 -0
- readthrough/onboard_model.py +319 -0
- readthrough/process.py +169 -0
- readthrough/profile.py +699 -0
- readthrough/py.typed +0 -0
- readthrough/registry.py +157 -0
- readthrough/review.py +394 -0
- readthrough/rules.py +111 -0
- readthrough/runtimes/__init__.py +297 -0
- readthrough/runtimes/anthropic.py +278 -0
- readthrough/runtimes/copilot.py +313 -0
- readthrough/runtimes/openai.py +307 -0
- readthrough/serve.py +817 -0
- readthrough/study.py +327 -0
- readthrough/system.py +205 -0
- readthrough/terminals.py +168 -0
- readthrough/tuning.py +266 -0
- readthrough/usage.py +169 -0
- readthrough/web_setup.py +635 -0
- readthrough-0.4.0.dist-info/METADATA +123 -0
- readthrough-0.4.0.dist-info/RECORD +73 -0
- readthrough-0.4.0.dist-info/WHEEL +4 -0
- readthrough-0.4.0.dist-info/entry_points.txt +2 -0
- readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""GitLab (gitlab.com or self-hosted), through the REST API.
|
|
2
|
+
|
|
3
|
+
The token comes from ``GITLAB_TOKEN`` if set, else from a signed-in ``glab`` CLI, else calls are anonymous,
|
|
4
|
+
which is enough for public projects. Projects nest (``group/subgroup/project``); the whole path is the repo.
|
|
5
|
+
|
|
6
|
+
What GitLab has and GitHub doesn't, and the other way round: an MR's "approved" is a count of approvals
|
|
7
|
+
against rules, so the review decision is derived (approved by rules, changes requested through a blocking
|
|
8
|
+
discussion, or review required). Author association comes from the author's access level in the project.
|
|
9
|
+
Required checks don't exist as names; the project setting "pipelines must succeed" is the nearest thing,
|
|
10
|
+
so required checks are reported as unsupported and the pipeline status drives the CI state.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any
|
|
18
|
+
from urllib.parse import quote
|
|
19
|
+
|
|
20
|
+
from readthrough.faults import ForgeError, NotFound, TooLarge
|
|
21
|
+
from readthrough.forges import FORGES, CiContext, Forge, Rest, cached_cli_token, credential, link_next
|
|
22
|
+
from readthrough.model import (
|
|
23
|
+
Author,
|
|
24
|
+
Capability,
|
|
25
|
+
ChangedFile,
|
|
26
|
+
Check,
|
|
27
|
+
Issue,
|
|
28
|
+
MergedPullRequest,
|
|
29
|
+
PullRequest,
|
|
30
|
+
Review,
|
|
31
|
+
Thread,
|
|
32
|
+
known,
|
|
33
|
+
unavailable,
|
|
34
|
+
unsupported,
|
|
35
|
+
)
|
|
36
|
+
from readthrough.process import quiet_output
|
|
37
|
+
|
|
38
|
+
log = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
# GitLab access levels -> the association vocabulary the profile's [authors] rules use.
|
|
41
|
+
ACCESS = {50: "OWNER", 40: "MEMBER", 30: "MEMBER", 20: "COLLABORATOR", 10: "COLLABORATOR", 5: "COLLABORATOR"}
|
|
42
|
+
PIPELINE = {
|
|
43
|
+
"success": ("COMPLETED", "SUCCESS"), "failed": ("COMPLETED", "FAILURE"), "canceled": ("COMPLETED", "CANCELLED"),
|
|
44
|
+
"skipped": ("COMPLETED", "SKIPPED"), "manual": ("COMPLETED", "ACTION_REQUIRED"), "running": ("IN_PROGRESS", None),
|
|
45
|
+
"pending": ("QUEUED", None), "created": ("QUEUED", None), "waiting_for_resource": ("QUEUED", None),
|
|
46
|
+
"preparing": ("QUEUED", None), "scheduled": ("QUEUED", None),
|
|
47
|
+
} # fmt: skip
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class GitLabOptions:
|
|
52
|
+
host: str = "gitlab.com"
|
|
53
|
+
credential_env: str = (
|
|
54
|
+
"GITLAB_TOKEN" # read if set; otherwise `glab auth status --show-token` when glab is signed in
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _glab_token(host: str) -> str | None:
|
|
59
|
+
"""The token glab holds for ``host``. glab prints its status report to stderr, one ``Token: ...`` line per host."""
|
|
60
|
+
|
|
61
|
+
def ask() -> str | None:
|
|
62
|
+
out = quiet_output(["glab", "auth", "status", "--hostname", host, "--show-token"], with_stderr=True)
|
|
63
|
+
return parse_glab_token(out or "")
|
|
64
|
+
|
|
65
|
+
return cached_cli_token(f"glab {host}", ask)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_glab_token(report: str) -> str | None:
|
|
69
|
+
for line in report.splitlines():
|
|
70
|
+
if "Token:" in line:
|
|
71
|
+
token = line.split("Token:", 1)[1].strip()
|
|
72
|
+
return token if token and not token.startswith("*") else None # stars mean it wasn't asked to show it
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@FORGES.add("gitlab", "GitLab, gitlab.com or self-hosted, through its REST API", options=GitLabOptions)
|
|
77
|
+
class GitLab(Forge):
|
|
78
|
+
name = "gitlab"
|
|
79
|
+
label = "GitLab"
|
|
80
|
+
config_dir = ".gitlab"
|
|
81
|
+
pr_noun = "merge request"
|
|
82
|
+
files_tab = "/diffs"
|
|
83
|
+
shape = "group/project (or group/subgroup/project)"
|
|
84
|
+
capabilities = frozenset({"diffs", "default_branch_ci", "rate_limit"})
|
|
85
|
+
access = "the GitLab REST API over HTTPS"
|
|
86
|
+
credentials = (
|
|
87
|
+
"GITLAB_TOKEN if set",
|
|
88
|
+
"else glab, if signed in to this host",
|
|
89
|
+
"else anonymously (public projects; gitlab.com throttles this hard)",
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def __init__(self, repo: str, options: Any = None, tuning: Any = None, *, account: str | None = None) -> None:
|
|
93
|
+
super().__init__(repo, options or GitLabOptions(), tuning, account=account)
|
|
94
|
+
self.host: str = self.options.host
|
|
95
|
+
env = self.options.credential_env
|
|
96
|
+
self.rest = Rest(
|
|
97
|
+
f"https://{self.host}/api/v4/",
|
|
98
|
+
lambda: credential(env=env, cli=lambda: _glab_token(self.host), cli_name="glab"),
|
|
99
|
+
self.tuning,
|
|
100
|
+
)
|
|
101
|
+
self.project = quote(repo, safe="")
|
|
102
|
+
self._default_branch: str | None = None
|
|
103
|
+
self._members: dict[str, int] | None = None
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def validate_repo(cls, repo: str) -> str | None:
|
|
107
|
+
parts = repo.split("/")
|
|
108
|
+
if len(parts) < 2 or not all(parts):
|
|
109
|
+
return f"{repo!r} isn't group/project (groups may nest: group/subgroup/project)"
|
|
110
|
+
return cls.bad_segment(parts)
|
|
111
|
+
|
|
112
|
+
def web_url(self) -> str:
|
|
113
|
+
return f"https://{self.host}/{self.repo}"
|
|
114
|
+
|
|
115
|
+
def pr_url(self, number: int) -> str:
|
|
116
|
+
return f"{self.web_url()}/-/merge_requests/{number}"
|
|
117
|
+
|
|
118
|
+
def pr_ref(self, number: int) -> str:
|
|
119
|
+
return f"merge-requests/{number}/head"
|
|
120
|
+
|
|
121
|
+
def file_url(self, path: str, branch: str) -> str:
|
|
122
|
+
return f"{self.web_url()}/-/blob/{branch}/{path}"
|
|
123
|
+
|
|
124
|
+
def new_file_url(self, path: str, branch: str) -> str | None:
|
|
125
|
+
return f"{self.web_url()}/-/new/{quote(branch, safe='')}?file_name={quote(path)}"
|
|
126
|
+
|
|
127
|
+
def describe_auth(self) -> str:
|
|
128
|
+
return self.rest.cred.source
|
|
129
|
+
|
|
130
|
+
# ---- REST helpers
|
|
131
|
+
|
|
132
|
+
def _get(self, path: str, **params: Any) -> Any:
|
|
133
|
+
resp = self.retrying(f"GET {path}", lambda: self.rest.call("GET", path, params=params))
|
|
134
|
+
return resp.json() if resp else None
|
|
135
|
+
|
|
136
|
+
def _get_or_none(self, path: str, **params: Any) -> Any:
|
|
137
|
+
resp = self.retrying(f"GET {path}", lambda: self.rest.call("GET", path, params=params, absent=(NotFound,)))
|
|
138
|
+
return resp.json() if resp else None
|
|
139
|
+
|
|
140
|
+
def _pages(self, endpoint: str, *, limit: int, **params: Any) -> list[Any]:
|
|
141
|
+
items: list[Any] = []
|
|
142
|
+
url: str | None = self.rest.url(endpoint, {**params, "per_page": min(100, limit)})
|
|
143
|
+
while url and len(items) < limit:
|
|
144
|
+
resp = self.retrying(f"GET {endpoint}", lambda u=url: self.rest.call("GET", u))
|
|
145
|
+
if resp is None:
|
|
146
|
+
break
|
|
147
|
+
items.extend(resp.json() or [])
|
|
148
|
+
url = link_next(resp.headers)
|
|
149
|
+
return items[:limit]
|
|
150
|
+
|
|
151
|
+
def _branch(self) -> str:
|
|
152
|
+
if self._default_branch is None:
|
|
153
|
+
self._default_branch = self.repo_info()["default_branch"] or "main"
|
|
154
|
+
return self._default_branch
|
|
155
|
+
|
|
156
|
+
# ---- the repo
|
|
157
|
+
|
|
158
|
+
def repo_info(self) -> dict[str, Any]:
|
|
159
|
+
info = self._get(f"projects/{self.project}")
|
|
160
|
+
return {
|
|
161
|
+
"full_name": info.get("path_with_namespace"), "default_branch": info.get("default_branch"),
|
|
162
|
+
"private": info.get("visibility") != "public", "description": info.get("description"),
|
|
163
|
+
} # fmt: skip
|
|
164
|
+
|
|
165
|
+
def rate_limit(self) -> dict[str, int] | None:
|
|
166
|
+
resp = self.rest.call("GET", f"projects/{self.project}", absent=(ForgeError,))
|
|
167
|
+
if resp is None or "ratelimit-remaining" not in resp.headers:
|
|
168
|
+
return None
|
|
169
|
+
return {"rest": int(resp.headers["ratelimit-remaining"])}
|
|
170
|
+
|
|
171
|
+
def tree(self, branch: str) -> tuple[list[str], bool]:
|
|
172
|
+
limit = self.tuning.max_tree_files
|
|
173
|
+
items = self._pages(f"projects/{self.project}/repository/tree", limit=limit + 1, ref=branch, recursive="true")
|
|
174
|
+
paths = [e["path"] for e in items if e.get("type") == "blob"]
|
|
175
|
+
return paths[:limit], len(items) <= limit
|
|
176
|
+
|
|
177
|
+
def read_file(self, path: str) -> str | None:
|
|
178
|
+
resp = self.retrying(f"GET file {path}", lambda: self.rest.call(
|
|
179
|
+
"GET", f"projects/{self.project}/repository/files/{quote(path, safe='')}/raw",
|
|
180
|
+
params={"ref": self._branch()}, headers={"Accept": "*/*"}, absent=(NotFound,),
|
|
181
|
+
)) # fmt: skip
|
|
182
|
+
return resp.text if resp else None
|
|
183
|
+
|
|
184
|
+
def list_dir(self, path: str) -> list[str]:
|
|
185
|
+
items = self._pages(f"projects/{self.project}/repository/tree", limit=1000, path=path, ref=self._branch())
|
|
186
|
+
return [e["name"] for e in items if e.get("type") == "blob"]
|
|
187
|
+
|
|
188
|
+
# ---- members, for author association
|
|
189
|
+
|
|
190
|
+
def _access(self, login: str) -> Capability[str]:
|
|
191
|
+
if self._members is None:
|
|
192
|
+
try:
|
|
193
|
+
members = self._pages(f"projects/{self.project}/members/all", limit=2000)
|
|
194
|
+
self._members = {m["username"].lower(): m["access_level"] for m in members}
|
|
195
|
+
except ForgeError as exc:
|
|
196
|
+
self._members = {}
|
|
197
|
+
self._members_error = exc.reason
|
|
198
|
+
if not self._members and getattr(self, "_members_error", ""):
|
|
199
|
+
return unavailable(f"members: {self._members_error}")
|
|
200
|
+
level = self._members.get(login.lower())
|
|
201
|
+
return known(ACCESS.get(level or 0, "CONTRIBUTOR"))
|
|
202
|
+
|
|
203
|
+
# ---- merge requests
|
|
204
|
+
|
|
205
|
+
def fetch_prs(self, limit: int) -> tuple[str, list[PullRequest], int]:
|
|
206
|
+
raw = self._pages(f"projects/{self.project}/merge_requests", limit=limit, state="opened", order_by="updated_at",
|
|
207
|
+
sort="desc", with_labels_details="false") # fmt: skip
|
|
208
|
+
total = len(raw)
|
|
209
|
+
resp = self.rest.call("GET", f"projects/{self.project}/merge_requests", params={"state": "opened", "per_page": 1},
|
|
210
|
+
absent=(ForgeError,)) # fmt: skip
|
|
211
|
+
if resp is not None and resp.headers.get("x-total"):
|
|
212
|
+
total = int(resp.headers["x-total"])
|
|
213
|
+
viewer = ""
|
|
214
|
+
me = self._get_or_none("user") if self.rest.cred.token else None
|
|
215
|
+
if me:
|
|
216
|
+
viewer = me.get("username") or ""
|
|
217
|
+
from readthrough.logs import pool_map
|
|
218
|
+
|
|
219
|
+
prs = pool_map(self._complete, raw, self.tuning.concurrency)
|
|
220
|
+
return viewer, prs, total
|
|
221
|
+
|
|
222
|
+
def _complete(self, mr: dict[str, Any]) -> PullRequest:
|
|
223
|
+
iid = mr["iid"]
|
|
224
|
+
base = f"projects/{self.project}/merge_requests/{iid}"
|
|
225
|
+
detail = self._get(base) # has diff_stats-ish counts, pipeline, detailed_merge_status
|
|
226
|
+
changes = self._pages(f"{base}/diffs", limit=self.tuning.max_files_per_pr)
|
|
227
|
+
files = [
|
|
228
|
+
ChangedFile(
|
|
229
|
+
c.get("new_path") or c.get("old_path"),
|
|
230
|
+
*_count_lines(c.get("diff") or ""),
|
|
231
|
+
"ADDED" if c.get("new_file") else "DELETED" if c.get("deleted_file") else "RENAMED" if c.get("renamed_file") else "MODIFIED",
|
|
232
|
+
)
|
|
233
|
+
for c in changes
|
|
234
|
+
] # fmt: skip
|
|
235
|
+
approvals = self._get_or_none(f"{base}/approvals") or {}
|
|
236
|
+
reviews = [Review(a["user"]["username"], "APPROVED", None) for a in approvals.get("approved_by") or []]
|
|
237
|
+
reviews += [Review(r["username"], "COMMENTED", None) for r in mr.get("reviewers") or []
|
|
238
|
+
if r["username"] not in {x.author for x in reviews}] # fmt: skip
|
|
239
|
+
threads: list[Thread] = []
|
|
240
|
+
try:
|
|
241
|
+
for d in self._pages(f"{base}/discussions", limit=self.tuning.max_review_threads_per_pr):
|
|
242
|
+
notes = [n for n in d.get("notes") or [] if not n.get("system")]
|
|
243
|
+
if not notes or not notes[0].get("resolvable"):
|
|
244
|
+
continue
|
|
245
|
+
first = notes[0]
|
|
246
|
+
pos = first.get("position") or {}
|
|
247
|
+
threads.append(Thread(first["author"]["username"], first.get("body") or "", "", pos.get("new_path"),
|
|
248
|
+
pos.get("new_line"), bool(first.get("resolved")), False)) # fmt: skip
|
|
249
|
+
threads_cap: Capability[list[Thread]] = known(threads)
|
|
250
|
+
except ForgeError as exc:
|
|
251
|
+
threads_cap = unavailable(exc.reason)
|
|
252
|
+
pipeline = detail.get("head_pipeline") or mr.get("head_pipeline")
|
|
253
|
+
checks: Capability[list[Check]]
|
|
254
|
+
if pipeline:
|
|
255
|
+
status, conclusion = PIPELINE.get(pipeline.get("status") or "", ("QUEUED", None))
|
|
256
|
+
checks = known([Check("pipeline", status, conclusion, pipeline.get("web_url"), pipeline.get("created_at"),
|
|
257
|
+
pipeline.get("updated_at"))]) # fmt: skip
|
|
258
|
+
else:
|
|
259
|
+
checks = known([])
|
|
260
|
+
# The decision rests on the discussions: without them it can't be known, and isn't guessed.
|
|
261
|
+
decision: Capability[str]
|
|
262
|
+
if not threads_cap.known:
|
|
263
|
+
decision = unavailable(f"review decision needs the discussions: {threads_cap.reason}")
|
|
264
|
+
elif any(not t.resolved for t in threads):
|
|
265
|
+
decision = known("CHANGES_REQUESTED")
|
|
266
|
+
else:
|
|
267
|
+
decision = known("APPROVED" if approvals.get("approved") else "REVIEW_REQUIRED")
|
|
268
|
+
status = detail.get("detailed_merge_status") or detail.get("merge_status") or ""
|
|
269
|
+
mergeable = (
|
|
270
|
+
"CONFLICTING"
|
|
271
|
+
if status in ("conflict", "cannot_be_merged")
|
|
272
|
+
else "MERGEABLE"
|
|
273
|
+
if status in ("mergeable", "can_be_merged")
|
|
274
|
+
else "UNKNOWN"
|
|
275
|
+
)
|
|
276
|
+
author = mr.get("author") or {}
|
|
277
|
+
return PullRequest(
|
|
278
|
+
number=iid, title=mr["title"], url=mr["web_url"], body=mr.get("description") or "", draft=bool(mr.get("draft")),
|
|
279
|
+
created=mr["created_at"], updated=mr["updated_at"],
|
|
280
|
+
additions=sum(f.additions for f in files), deletions=sum(f.deletions for f in files),
|
|
281
|
+
changed_files=(detail.get("changes_count") and int(str(detail["changes_count"]).rstrip("+"))) or len(files),
|
|
282
|
+
head=mr.get("sha") or "", base=mr.get("target_branch") or "main",
|
|
283
|
+
author=Author(author.get("username") or "ghost", bot=bool(author.get("bot"))),
|
|
284
|
+
files=files, labels=list(mr.get("labels") or []),
|
|
285
|
+
requested=[r["username"] for r in mr.get("reviewers") or []], reviews=reviews,
|
|
286
|
+
comments=int(mr.get("user_notes_count") or 0), last_commit=(pipeline or {}).get("created_at"),
|
|
287
|
+
issues=[Issue(i["iid"], i["title"], i["web_url"]) for i in self._get_or_none(f"{base}/closes_issues") or []],
|
|
288
|
+
association=self._access(author.get("username") or ""), decision=decision, mergeable=known(mergeable),
|
|
289
|
+
threads=threads_cap, checks=checks,
|
|
290
|
+
truncated={"files": (len(files), int(str(detail.get("changes_count", "0")).rstrip("+") or 0))}
|
|
291
|
+
if str(detail.get("changes_count", "")).endswith("+") else {},
|
|
292
|
+
) # fmt: skip
|
|
293
|
+
|
|
294
|
+
def merged_prs(self, count: int) -> tuple[str, list[MergedPullRequest]]:
|
|
295
|
+
raw = self._pages(
|
|
296
|
+
f"projects/{self.project}/merge_requests", limit=count, state="merged", order_by="updated_at", sort="desc"
|
|
297
|
+
)
|
|
298
|
+
merged = []
|
|
299
|
+
for mr in raw:
|
|
300
|
+
changes = self._pages(f"projects/{self.project}/merge_requests/{mr['iid']}/diffs", limit=100)
|
|
301
|
+
author = mr.get("author") or {}
|
|
302
|
+
merged.append(MergedPullRequest(
|
|
303
|
+
mr["iid"], Author(author.get("username") or "ghost", bool(author.get("bot"))),
|
|
304
|
+
self._access(author.get("username") or ""),
|
|
305
|
+
[ChangedFile(c.get("new_path") or c.get("old_path"), *_count_lines(c.get("diff") or "")) for c in changes],
|
|
306
|
+
)) # fmt: skip
|
|
307
|
+
return self._branch(), merged
|
|
308
|
+
|
|
309
|
+
def fetch_diff(self, number: int) -> str:
|
|
310
|
+
resp = self.retrying(f"MR diff !{number}", lambda: self.rest.call(
|
|
311
|
+
"GET", f"projects/{self.project}/merge_requests/{number}/raw_diffs", headers={"Accept": "text/plain"},
|
|
312
|
+
)) # fmt: skip
|
|
313
|
+
if resp is None:
|
|
314
|
+
raise TooLarge(f"MR diff !{number}: not served", what=f"MR diff !{number}")
|
|
315
|
+
return resp.text
|
|
316
|
+
|
|
317
|
+
# ---- CI
|
|
318
|
+
|
|
319
|
+
def ci_context(self, bases: set[str]) -> CiContext:
|
|
320
|
+
branch = self._branch()
|
|
321
|
+
pipelines = (
|
|
322
|
+
self._get_or_none(
|
|
323
|
+
f"projects/{self.project}/pipelines", ref=branch, per_page=1, order_by="updated_at", sort="desc"
|
|
324
|
+
)
|
|
325
|
+
or []
|
|
326
|
+
)
|
|
327
|
+
failing: set[str] = {"pipeline"} if pipelines and pipelines[0].get("status") == "failed" else set()
|
|
328
|
+
required = {b: unsupported("GitLab has no named required checks; the pipeline must pass") for b in bases}
|
|
329
|
+
return CiContext(required, known(failing), branch)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _count_lines(diff: str) -> tuple[int, int]:
|
|
333
|
+
add = sum(1 for line in diff.splitlines() if line.startswith("+") and not line.startswith("+++"))
|
|
334
|
+
dele = sum(1 for line in diff.splitlines() if line.startswith("-") and not line.startswith("---"))
|
|
335
|
+
return add, dele
|
readthrough/ledger.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""The review ledger: what you did with each PR, pinned to the head SHA you saw."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as dt
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from readthrough.files import locked, write_atomic
|
|
11
|
+
|
|
12
|
+
STATUSES = ("understood", "reviewed", "commented", "approved", "changes-requested", "skipped")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def load(path: Path) -> dict[str, Any]:
|
|
16
|
+
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _save(path: Path, ledger: dict[str, Any]) -> None:
|
|
20
|
+
write_atomic(path, json.dumps(ledger, indent=1))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def record(
|
|
24
|
+
path: Path,
|
|
25
|
+
number: int,
|
|
26
|
+
*,
|
|
27
|
+
status: str | None = None,
|
|
28
|
+
note: str | None = None,
|
|
29
|
+
head: str = "",
|
|
30
|
+
session: str | None = None,
|
|
31
|
+
) -> dict[str, Any]:
|
|
32
|
+
if status is not None and status not in STATUSES:
|
|
33
|
+
raise ValueError(f"status must be one of {', '.join(STATUSES)}")
|
|
34
|
+
# Read, change, write as one step: two browser tabs, or the server and `readthrough ledger` in a terminal,
|
|
35
|
+
# would otherwise each load the file and the slower one's write would drop the other's change.
|
|
36
|
+
with locked(path):
|
|
37
|
+
ledger = load(path)
|
|
38
|
+
entry = ledger.setdefault(str(number), {})
|
|
39
|
+
if status is not None:
|
|
40
|
+
entry.update(status=status, date=dt.datetime.now(dt.UTC).isoformat(), head=head or entry.get("head", ""))
|
|
41
|
+
if note is not None:
|
|
42
|
+
entry["note"] = note
|
|
43
|
+
if session is not None:
|
|
44
|
+
entry["session"] = session
|
|
45
|
+
_save(path, ledger)
|
|
46
|
+
return entry
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clear_status(path: Path, number: int) -> dict[str, Any]:
|
|
50
|
+
"""Forget the status for a PR but keep its note and agent session."""
|
|
51
|
+
with locked(path):
|
|
52
|
+
ledger = load(path)
|
|
53
|
+
entry = ledger.get(str(number), {})
|
|
54
|
+
for key in ("status", "date", "head"):
|
|
55
|
+
entry.pop(key, None)
|
|
56
|
+
if entry:
|
|
57
|
+
ledger[str(number)] = entry
|
|
58
|
+
else:
|
|
59
|
+
ledger.pop(str(number), None)
|
|
60
|
+
_save(path, ledger)
|
|
61
|
+
return entry
|
readthrough/limits.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Fixed safety limits. Deliberately not tunable: a config edit shouldn't be able to loosen a safeguard.
|
|
2
|
+
|
|
3
|
+
Everything here bounds input from outside readthrough (web requests, people's text, model output) or decides
|
|
4
|
+
what the browser may change. Operational settings that are safe to change live in ``tuning.py``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
# The largest request body the local server reads (a profile being edited in the browser is the biggest).
|
|
12
|
+
MAX_REQUEST_BYTES = 250_000
|
|
13
|
+
# An oversized body up to this size is read and discarded before the 413, so the client sees the answer
|
|
14
|
+
# instead of a connection reset (Windows resets sockets closed with unread data). Bigger ones are just cut off.
|
|
15
|
+
MAX_DISCARD_BYTES = 8_000_000
|
|
16
|
+
# The longest text field kept in a study-log entry (an answer, a note, a model's assessment).
|
|
17
|
+
MAX_STUDY_TEXT = 8000
|
|
18
|
+
# A login as the browser may send it: a GitHub login (enterprise managed users look like shortcode_suffix, so
|
|
19
|
+
# underscores are allowed), or the email address Azure DevOps and GitLab use as a unique name.
|
|
20
|
+
LOGIN_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9_.+-]{0,60})(?:@[A-Za-z0-9.-]{1,120})?(?:\[bot\])?$")
|
|
21
|
+
# A Copilot model name as accepted from the browser's settings page.
|
|
22
|
+
MODEL_RE = re.compile(r"^[\w.:-]{1,80}$")
|
|
23
|
+
# Bounds on per-repo settings the browser may change.
|
|
24
|
+
BROWSER_EDITABLE_INTS = {"session_minutes": (10, 480), "limit": (1, 500)}
|
|
25
|
+
# The most a code search tool returns to the study assistant, whatever the tool-output setting says.
|
|
26
|
+
MAX_SEARCH_OUTPUT = 20_000
|
readthrough/logs.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Logging that stays readable when several repos build at once.
|
|
2
|
+
|
|
3
|
+
Every record carries the repo and a short build id (from context variables, so they follow the work into
|
|
4
|
+
thread pools via ``pool_map``). The server and readthrough.log use one timestamped format; interactive commands
|
|
5
|
+
print plain messages. ``format = "json"`` writes one JSON object per line for log tools.
|
|
6
|
+
|
|
7
|
+
Expected failures (a network blip GitHub recovers from) are logged as one line. Unexpected ones get a
|
|
8
|
+
traceback. Each failure gets a short error id that also appears in the dashboard, so a screenshot leads
|
|
9
|
+
straight to the log lines.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import contextvars
|
|
16
|
+
import json
|
|
17
|
+
import logging
|
|
18
|
+
import secrets
|
|
19
|
+
import sys
|
|
20
|
+
import time
|
|
21
|
+
from collections.abc import Callable, Generator, Iterable
|
|
22
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
23
|
+
from logging.handlers import RotatingFileHandler
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import TypeVar
|
|
26
|
+
|
|
27
|
+
from readthrough.tuning import LoggingTuning
|
|
28
|
+
|
|
29
|
+
repo_var: contextvars.ContextVar[str] = contextvars.ContextVar("readthrough_repo", default="")
|
|
30
|
+
build_var: contextvars.ContextVar[str] = contextvars.ContextVar("readthrough_build", default="")
|
|
31
|
+
|
|
32
|
+
T = TypeVar("T")
|
|
33
|
+
R = TypeVar("R")
|
|
34
|
+
ROOT = "readthrough"
|
|
35
|
+
TEXT_FORMAT = "%(asctime)s.%(msecs)03d %(levelname)-7s %(ctx)s%(message)s"
|
|
36
|
+
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def new_id() -> str:
|
|
40
|
+
return secrets.token_hex(2)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ContextFilter(logging.Filter):
|
|
44
|
+
"""Adds the repo and build context to every record, and strips every secret this process has seen from it.
|
|
45
|
+
|
|
46
|
+
Redaction here, on the way to a handler, means no call site has to remember it: a token a program echoed into
|
|
47
|
+
an error message never reaches readthrough.log, the console, or a ``doctor --bundle``.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
51
|
+
repo, build = repo_var.get(), build_var.get()
|
|
52
|
+
record.repo, record.build = repo, build
|
|
53
|
+
record.ctx = f"[{repo}{' ' + build if build else ''}] " if repo else ""
|
|
54
|
+
from readthrough.process import redact # process logs through this module, so the import waits
|
|
55
|
+
|
|
56
|
+
record.msg, record.args = redact(record.getMessage()), ()
|
|
57
|
+
if record.exc_info and record.exc_text is None and record.exc_info[1] is not None:
|
|
58
|
+
record.exc_text = redact(logging.Formatter().formatException(record.exc_info))
|
|
59
|
+
return True
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class JsonFormatter(logging.Formatter):
|
|
63
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
64
|
+
out = {
|
|
65
|
+
"ts": self.formatTime(record, DATE_FORMAT) + f".{int(record.msecs):03d}",
|
|
66
|
+
"level": record.levelname.lower(),
|
|
67
|
+
"logger": record.name,
|
|
68
|
+
"repo": getattr(record, "repo", "") or None,
|
|
69
|
+
"build": getattr(record, "build", "") or None,
|
|
70
|
+
"msg": record.getMessage(),
|
|
71
|
+
}
|
|
72
|
+
for key in ("error_id", "step", "duration_s", "attempt"):
|
|
73
|
+
if hasattr(record, key):
|
|
74
|
+
out[key] = getattr(record, key)
|
|
75
|
+
if record.exc_info:
|
|
76
|
+
out["exc"] = self.formatException(record.exc_info)
|
|
77
|
+
return json.dumps({k: v for k, v in out.items() if v is not None}, ensure_ascii=False)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _formatter(fmt: str, *, plain: bool = False) -> logging.Formatter:
|
|
81
|
+
if fmt == "json":
|
|
82
|
+
return JsonFormatter()
|
|
83
|
+
if plain:
|
|
84
|
+
return logging.Formatter("%(ctx)s%(message)s")
|
|
85
|
+
return logging.Formatter(TEXT_FORMAT, DATE_FORMAT)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_configured = False
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def setup(log_path: Path, tuning: LoggingTuning, *, verbose: bool = False, console: str = "plain") -> None:
|
|
92
|
+
"""Configure the ``readthrough`` logger once. ``console`` is "plain" (commands), "full" (the server), or "none"."""
|
|
93
|
+
global _configured # noqa: PLW0603 - the one process-wide "already configured" flag
|
|
94
|
+
if _configured:
|
|
95
|
+
return
|
|
96
|
+
logger = logging.getLogger(ROOT)
|
|
97
|
+
logger.setLevel(logging.DEBUG if verbose else getattr(logging, tuning.level.upper()))
|
|
98
|
+
logger.propagate = False
|
|
99
|
+
context = ContextFilter()
|
|
100
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
file_handler = RotatingFileHandler(
|
|
102
|
+
log_path, maxBytes=tuning.file_max_kb * 1024, backupCount=tuning.file_backups, encoding="utf-8"
|
|
103
|
+
)
|
|
104
|
+
file_handler.setFormatter(_formatter(tuning.format))
|
|
105
|
+
file_handler.addFilter(context)
|
|
106
|
+
logger.addHandler(file_handler)
|
|
107
|
+
if console != "none" and sys.stderr is not None: # stderr is None under pythonw (scheduled task, URL handler)
|
|
108
|
+
handler = logging.StreamHandler()
|
|
109
|
+
handler.setFormatter(_formatter(tuning.format, plain=console == "plain"))
|
|
110
|
+
handler.addFilter(context)
|
|
111
|
+
logger.addHandler(handler)
|
|
112
|
+
_configured = True
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def reset() -> None:
|
|
116
|
+
"""Forget the configuration and close its handlers, so the next ``setup`` starts over (tests)."""
|
|
117
|
+
global _configured # noqa: PLW0603 - see setup
|
|
118
|
+
logger = logging.getLogger(ROOT)
|
|
119
|
+
for handler in logger.handlers[:]:
|
|
120
|
+
logger.removeHandler(handler)
|
|
121
|
+
handler.close()
|
|
122
|
+
logger.propagate = True
|
|
123
|
+
logger.setLevel(logging.NOTSET)
|
|
124
|
+
_configured = False
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@contextlib.contextmanager
|
|
128
|
+
def context(repo: str = "", build: str = "") -> Generator[None]:
|
|
129
|
+
"""Tag every log line inside the block with this repo and build id."""
|
|
130
|
+
tokens = [repo_var.set(repo)] if repo else []
|
|
131
|
+
if build:
|
|
132
|
+
tokens.append(build_var.set(build))
|
|
133
|
+
try:
|
|
134
|
+
yield
|
|
135
|
+
finally:
|
|
136
|
+
for token in reversed(tokens):
|
|
137
|
+
token.var.reset(token)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def pool_map(fn: Callable[[T], R], items: Iterable[T], workers: int) -> list[R]:
|
|
141
|
+
"""``ThreadPoolExecutor.map`` that carries the caller's log context into the worker threads."""
|
|
142
|
+
items = list(items)
|
|
143
|
+
if not items:
|
|
144
|
+
return []
|
|
145
|
+
ctx = contextvars.copy_context()
|
|
146
|
+
with ThreadPoolExecutor(max(1, min(workers, len(items)))) as pool:
|
|
147
|
+
return list(pool.map(lambda item: ctx.copy().run(fn, item), items))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class Steps:
|
|
151
|
+
"""Times the steps of a build, so a failure says which step failed and a success says where time went."""
|
|
152
|
+
|
|
153
|
+
def __init__(self, log: logging.Logger) -> None:
|
|
154
|
+
self.log = log
|
|
155
|
+
self.current = "starting"
|
|
156
|
+
self.timings: list[tuple[str, float]] = []
|
|
157
|
+
|
|
158
|
+
@contextlib.contextmanager
|
|
159
|
+
def step(self, name: str) -> Generator[None]:
|
|
160
|
+
self.current = name
|
|
161
|
+
started = time.monotonic()
|
|
162
|
+
self.log.debug("step %s: started", name)
|
|
163
|
+
yield
|
|
164
|
+
took = time.monotonic() - started
|
|
165
|
+
self.timings.append((name, took))
|
|
166
|
+
self.log.debug("step %s: done in %.1fs", name, took, extra={"step": name, "duration_s": round(took, 2)})
|
|
167
|
+
|
|
168
|
+
def summary(self) -> str:
|
|
169
|
+
return ", ".join(f"{name} {took:.1f}s" for name, took in self.timings)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Team and org membership for author classification.
|
|
2
|
+
|
|
3
|
+
A profile can say "members of these teams / orgs are internal". Listing a big org (microsoft has far
|
|
4
|
+
more members than any API page) isn't practical, so each PR author is checked individually and the
|
|
5
|
+
answer is cached for a week.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Protocol
|
|
15
|
+
|
|
16
|
+
from readthrough.faults import ForgeError
|
|
17
|
+
from readthrough.files import write_atomic
|
|
18
|
+
from readthrough.logs import pool_map
|
|
19
|
+
from readthrough.tuning import ForgeTuning
|
|
20
|
+
|
|
21
|
+
log = logging.getLogger(__name__)
|
|
22
|
+
DAY = 24 * 3600
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Membership(Protocol):
|
|
26
|
+
"""All a membership check needs from a forge: one lookup, and the concurrency to run them at."""
|
|
27
|
+
|
|
28
|
+
tuning: ForgeTuning
|
|
29
|
+
|
|
30
|
+
def is_member(self, group: str, login: str) -> bool: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _check(forge: Membership, key: str) -> bool:
|
|
34
|
+
kind, org, *rest = key.split(":")
|
|
35
|
+
login = rest[-1]
|
|
36
|
+
return forge.is_member(org if kind == "org" else f"{org}/{rest[0]}", login)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def internal_members(
|
|
40
|
+
forge: Membership, *, teams: list[str], orgs: list[str], logins: set[str], cache_path: Path, ttl_days: float = 7.0
|
|
41
|
+
) -> tuple[set[str], list[str]]:
|
|
42
|
+
"""Logins (lower-case) that belong to one of ``teams`` ("org/team-slug") or ``orgs``, and checks that failed.
|
|
43
|
+
|
|
44
|
+
Answers are cached for ``ttl_days``. A check that fails (network, auth) isn't cached, and its login is
|
|
45
|
+
classified by the profile's other rules this time. Only the forge's "no" is a no: the adapter raises
|
|
46
|
+
for anything but a definite answer.
|
|
47
|
+
"""
|
|
48
|
+
if not (teams or orgs) or not logins:
|
|
49
|
+
return set(), []
|
|
50
|
+
try:
|
|
51
|
+
cache: dict[str, Any] = json.loads(cache_path.read_text(encoding="utf-8"))
|
|
52
|
+
except (FileNotFoundError, ValueError):
|
|
53
|
+
cache = {}
|
|
54
|
+
now = time.time()
|
|
55
|
+
keys = [f"org:{o}:{login}" for o in orgs for login in logins]
|
|
56
|
+
keys += [f"team:{t.split('/')[0]}:{t.split('/')[1]}:{login}" for t in teams if "/" in t for login in logins]
|
|
57
|
+
stale = [k for k in keys if k not in cache or now - cache[k][1] > ttl_days * DAY]
|
|
58
|
+
failed: list[str] = []
|
|
59
|
+
if stale:
|
|
60
|
+
log.info("Checking %d team/org memberships", len(stale))
|
|
61
|
+
|
|
62
|
+
def check(key: str) -> bool | ForgeError:
|
|
63
|
+
try:
|
|
64
|
+
return _check(forge, key)
|
|
65
|
+
except ForgeError as exc:
|
|
66
|
+
return exc
|
|
67
|
+
|
|
68
|
+
for key, result in zip(stale, pool_map(check, stale, forge.tuning.concurrency), strict=True):
|
|
69
|
+
if isinstance(result, ForgeError):
|
|
70
|
+
failed.append(f"{key.split(':', 1)[1]}: {result.reason}")
|
|
71
|
+
cache.pop(key, None)
|
|
72
|
+
else:
|
|
73
|
+
cache[key] = [result, now]
|
|
74
|
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
write_atomic(cache_path, json.dumps(cache))
|
|
76
|
+
return {k.rsplit(":", 1)[1].lower() for k in keys if k in cache and cache[k][0]}, failed
|