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,658 @@
1
+ """Azure DevOps Repos, through the REST API. A repo is ``organization/project/repository``.
2
+
3
+ The token comes from ``AZURE_DEVOPS_EXT_PAT`` if set (the variable the ``az devops`` extension reads too),
4
+ else from a signed-in ``az`` CLI (``az account get-access-token`` for the Azure DevOps resource), else calls
5
+ are anonymous, which works for public projects.
6
+
7
+ Azure DevOps serves no unified diff and reports no line counts, so a PR's diff is assembled here from both
8
+ versions of each changed file (two blob requests per file, capped by ``max_assembled_diff_files``), and the
9
+ build counts lines from it. It has no author association either, so one is derived: everyone who opens a PR
10
+ holds contribute rights (GitHub's COLLABORATOR), and the completed-PR history tells a returning author from
11
+ a first-timer; the organization's users and a project team's members (through nested groups, via the
12
+ identities API on the ``vssps`` host) back the ``memberships`` capability. There is no "closes issues" link
13
+ readthrough can read. Reviewer votes map to review states (10/5 approve, -5 wait, -10 reject), branch
14
+ policies supply required build names, and the head commit's statuses are the checks.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import re
21
+ import threading
22
+ from dataclasses import dataclass
23
+ from typing import Any
24
+ from urllib.parse import quote, unquote
25
+
26
+ from readthrough.faults import AuthError, ForgeError, NotFound, TooLarge
27
+ from readthrough.forges import (
28
+ FORGES,
29
+ CiContext,
30
+ Credential,
31
+ FilePair,
32
+ Forge,
33
+ Rest,
34
+ assemble_diff,
35
+ cached_cli_token,
36
+ credential,
37
+ )
38
+ from readthrough.logs import pool_map
39
+ from readthrough.model import (
40
+ PATH_SEGMENT,
41
+ Author,
42
+ Capability,
43
+ ChangedFile,
44
+ Check,
45
+ MergedPullRequest,
46
+ PullRequest,
47
+ Review,
48
+ Thread,
49
+ known,
50
+ unavailable,
51
+ unsupported,
52
+ )
53
+ from readthrough.process import quiet_output
54
+
55
+ log = logging.getLogger(__name__)
56
+
57
+ API = "7.1"
58
+ ADO_RESOURCE = "499b84ac-1321-427f-aa17-267ca6975798" # the Azure DevOps application id, for az access tokens
59
+ VOTES = {10: "APPROVED", 5: "APPROVED", 0: "COMMENTED", -5: "COMMENTED", -10: "CHANGES_REQUESTED"}
60
+ STATUS = {
61
+ "succeeded": "SUCCESS",
62
+ "failed": "FAILURE",
63
+ "error": "ERROR",
64
+ "pending": None,
65
+ "notSet": None,
66
+ "notApplicable": "SKIPPED",
67
+ }
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class AzureDevOpsOptions:
72
+ host: str = "dev.azure.com"
73
+ credential_env: str = "AZURE_DEVOPS_EXT_PAT"
74
+
75
+
76
+ # What `az` said when it had no token to give, per tenant, so `doctor` can repeat it. Never the token itself.
77
+ _az_notes: dict[str, str] = {}
78
+
79
+
80
+ def _az_token(tenant: str | None) -> str | None:
81
+ """An access token for Azure DevOps from a signed-in ``az``, for the organization's tenant when known.
82
+
83
+ Asking for the tenant matters: an account signed in to several tenants holds a token for the default
84
+ one, and an organization in another tenant refuses it. ``get-access-token`` never prompts; when it has
85
+ nothing it says so on stderr, and that note is kept for ``doctor``.
86
+ """
87
+ cmd = ["az", "account", "get-access-token", "--resource", ADO_RESOURCE, "--query", "accessToken", "-o", "tsv"]
88
+ if tenant:
89
+ cmd += ["--tenant", tenant]
90
+
91
+ def ask() -> str | None:
92
+ out, complaint = quiet_output(cmd, with_failure=True)
93
+ if out:
94
+ _az_notes.pop(tenant or "", None)
95
+ return out.strip()
96
+ _az_notes[tenant or ""] = _az_complaint(complaint)
97
+ return None
98
+
99
+ return cached_cli_token(f"az:{tenant or ''}", ask)
100
+
101
+
102
+ def _az_complaint(stderr: str) -> str:
103
+ """The one line of az's stderr worth repeating: the AADSTS code when there is one (it names the policy that
104
+ wants a sign-in), else the last error line, which is the message when az prints a whole traceback."""
105
+ lines = [line.strip() for line in stderr.splitlines() if line.strip()]
106
+ if not lines:
107
+ return "az isn't installed or isn't signed in"
108
+ picked = next((line for line in lines if "AADSTS" in line), None) or next(
109
+ (line for line in reversed(lines) if line.startswith("ERROR:") or re.match(r"^\w*(Error|Exception)\b", line)),
110
+ lines[0],
111
+ )
112
+ return picked.removeprefix("ERROR:").strip()[:200]
113
+
114
+
115
+ _tenants: dict[str, str | None] = {} # organization (lower-cased) -> its Entra tenant id, or None when it has none
116
+ _tenants_lock = threading.Lock()
117
+
118
+
119
+ @FORGES.add("ado", "Azure DevOps Repos, through its REST API", options=AzureDevOpsOptions)
120
+ class AzureDevOps(Forge):
121
+ name = "ado"
122
+ label = "Azure DevOps"
123
+ config_dir = ".azuredevops"
124
+ shape = "organization/project/repository"
125
+ capabilities = frozenset({"diffs", "required_checks", "default_branch_ci", "memberships"}) # diffs: from blobs
126
+ files_tab = "?_a=files"
127
+ access = "the Azure DevOps REST API over HTTPS (dev.azure.com, plus vssps.dev.azure.com for identities)"
128
+ credentials = (
129
+ "AZURE_DEVOPS_EXT_PAT if set (a personal access token)",
130
+ "else az, asked for a token in the organization's own tenant (never prompts)",
131
+ "else anonymously (public projects)",
132
+ )
133
+
134
+ def __init__(self, repo: str, options: Any = None, tuning: Any = None, *, account: str | None = None) -> None:
135
+ super().__init__(repo, options or AzureDevOpsOptions(), tuning, account=account)
136
+ self.host: str = self.options.host
137
+ self.org, self.project, self.repo_name = repo.split("/")
138
+ self.env = self.options.credential_env
139
+ # Without the header, an unauthorized call gets the sign-in page (a 203); with it, a 401 that names the
140
+ # organization's tenant, which is what tells `az` which of its identities to use.
141
+ self.headers = {"X-TFS-FedAuthRedirect": "Suppress"}
142
+ self.rest = Rest(
143
+ f"https://{self.host}/{quote(self.org)}/", self._find_credential, self.tuning, headers=self.headers
144
+ )
145
+ # Identities and the graph live on another host, which gets the same credential (a Rest sends its
146
+ # Authorization header only to its own host) and follows when the main one steps aside to anonymous.
147
+ self.vssps = Rest(
148
+ f"https://vssps.{self.host}/{quote(self.org)}/", lambda: self.rest.cred, self.tuning, headers=self.headers
149
+ )
150
+ self._default_branch: str | None = None
151
+ self._repo_id: str | None = None
152
+ self._merge_commits_of: dict[int, tuple[str, str]] = {} # from fetch_prs, so fetch_diff needn't ask again
153
+ self._association_of: dict[str, Capability[str]] = {} # per author id, from their completed-PR history
154
+ self._members_lock = threading.Lock()
155
+ self._org_logins: set[str] | None = None
156
+ self._team_descriptors: dict[str, str] = {}
157
+ self._id_of: dict[str, str] = {} # login -> identity id, from the PRs' authors
158
+
159
+ # ---- credentials
160
+
161
+ def _find_credential(self) -> Credential:
162
+ """A PAT from the environment (sent as Basic auth), else an az token for the organization's tenant
163
+ (Bearer), else anonymous, which public projects answer."""
164
+ cred = credential(env=self.env, cli=None, cli_name="", scheme="Basic")
165
+ if cred.token:
166
+ return cred
167
+ tenant = self.tenant()
168
+ return credential(env="", cli=lambda: _az_token(tenant), cli_name="az")
169
+
170
+ def tenant(self) -> str | None:
171
+ """The organization's Entra tenant id, from the 401 an anonymous listing of its projects gets (even an
172
+ organization with public projects refuses that); None for one with no tenant (a Microsoft-account
173
+ organization). Asked once per process; the answer names nobody."""
174
+ key = self.org.lower()
175
+ with _tenants_lock:
176
+ if key not in _tenants:
177
+ probe = Rest(self.rest.base, Credential("anonymous"), self.tuning, headers=self.headers)
178
+ try:
179
+ probe.call("GET", "_apis/projects", params={"$top": 1, "api-version": API})
180
+ _tenants[key] = None
181
+ except AuthError as exc:
182
+ _tenants[key] = exc.headers.get("x-vss-resourcetenant") or None
183
+ except ForgeError:
184
+ return None # couldn't ask this time; not remembered, so the next adapter asks again
185
+ return _tenants[key]
186
+
187
+ def sign_in_hint(self) -> str:
188
+ """What to run to be let in: a login scoped to the organization's tenant, which prompts once, where a
189
+ plain `az login` visits every tenant the account can reach and may prompt for each."""
190
+ tenant = self.tenant()
191
+ login = (
192
+ f"az login --tenant {tenant} --allow-no-subscriptions" if tenant else "az login --allow-no-subscriptions"
193
+ )
194
+ return f"{login} --scope {ADO_RESOURCE}/.default, or set {self.env} to a personal access token"
195
+
196
+ def describe_auth(self) -> str:
197
+ source = self.rest.cred.source
198
+ if source == "az":
199
+ tenant = self.tenant()
200
+ return f"az (tenant {tenant})" if tenant else "az"
201
+ if source == "anonymous" and (note := _az_notes.get(self.tenant() or "")):
202
+ return f"anonymous; az has no token for {self.org}: {note}"
203
+ return source
204
+
205
+ def retrying(self, what: str, call: Any) -> Any:
206
+ """Like the base, but an ``az`` identity the organization refuses steps aside for anonymous access.
207
+
208
+ The az token is opportunistic (nobody configured it), and a public project answers anonymous calls
209
+ that it refuses to a signed-in outsider. A token someone set on purpose is never second-guessed. When
210
+ anonymous is refused too, the identity is kept and the error says how to sign in to this organization.
211
+ """
212
+ try:
213
+ return super().retrying(what, call)
214
+ except AuthError as refused:
215
+ if self.rest.cred.source != "az":
216
+ raise
217
+ signed_in, self.rest = (
218
+ self.rest,
219
+ Rest(self.rest.base, Credential("anonymous"), self.tuning, headers=self.headers),
220
+ )
221
+ try:
222
+ result = super().retrying(what, call)
223
+ except AuthError as exc:
224
+ self.rest = signed_in
225
+ raise AuthError(
226
+ f"{self.org} refuses both the az identity and anonymous access; sign in to it with: {self.sign_in_hint()}",
227
+ what=what, stderr=exc.stderr, headers=exc.headers,
228
+ ) from refused # fmt: skip
229
+ log.warning(
230
+ "%s refuses the az identity; continuing anonymously, which this public project answers", self.org
231
+ )
232
+ self.vssps = Rest(self.vssps.base, Credential("anonymous"), self.tuning, headers=self.headers)
233
+ return result
234
+
235
+ @classmethod
236
+ def validate_repo(cls, repo: str) -> str | None:
237
+ # Project and repository names may contain spaces ("Delivery Team"); organizations may not.
238
+ parts = repo.split("/")
239
+ if len(parts) != 3 or not all(re.fullmatch(PATH_SEGMENT, p) for p in parts) or " " in parts[0]:
240
+ return f"{repo!r} isn't organization/project/repository"
241
+ return cls.bad_segment(parts, spaces=True)
242
+
243
+ @classmethod
244
+ def remote_matches(cls, url: str, repo: str) -> bool:
245
+ """``https://<org>@dev.azure.com/<org>/<project>/_git/<repo>`` or ``git@ssh.dev.azure.com:v3/<org>/<project>/<repo>``,
246
+ with the project percent-encoded in the https form ("Delivery%20Team")."""
247
+ org, project, name = (p.lower() for p in repo.split("/"))
248
+ path = unquote(url).lower().rstrip("/")
249
+ return path.endswith((f"/{org}/{project}/_git/{name}", f"v3/{org}/{project}/{name}"))
250
+
251
+ def web_url(self) -> str:
252
+ return f"https://{self.host}/{quote(self.org)}/{quote(self.project)}/_git/{quote(self.repo_name)}"
253
+
254
+ def pr_url(self, number: int) -> str:
255
+ return f"{self.web_url()}/pullrequest/{number}"
256
+
257
+ def pr_ref(self, number: int) -> str:
258
+ return f"pull/{number}/merge"
259
+
260
+ def file_url(self, path: str, branch: str) -> str:
261
+ return f"{self.web_url()}?path={quote('/' + path)}&version=GB{quote(branch)}"
262
+
263
+ # ---- REST helpers
264
+
265
+ @property
266
+ def _p(self) -> str:
267
+ return f"{quote(self.project)}/_apis/git/repositories/{quote(self.repo_name)}"
268
+
269
+ def _get(self, path: str, **params: Any) -> Any:
270
+ params.setdefault("api-version", API)
271
+ resp = self.retrying(f"GET {path}", lambda: self.rest.call("GET", path, params=params))
272
+ return resp.json() if resp else None
273
+
274
+ def _get_or_none(self, path: str, **params: Any) -> Any:
275
+ params.setdefault("api-version", API)
276
+ resp = self.retrying(f"GET {path}", lambda: self.rest.call("GET", path, params=params, absent=(NotFound,)))
277
+ return resp.json() if resp else None
278
+
279
+ def _branch(self) -> str:
280
+ if self._default_branch is None:
281
+ self._default_branch = self.repo_info()["default_branch"] or "main"
282
+ return self._default_branch
283
+
284
+ # ---- the repo
285
+
286
+ def repo_info(self) -> dict[str, Any]:
287
+ info = self._get(self._p)
288
+ self._repo_id = info.get("id")
289
+ branch = (info.get("defaultBranch") or "refs/heads/main").removeprefix("refs/heads/")
290
+ return {"full_name": f"{self.org}/{self.project}/{info.get('name')}", "default_branch": branch,
291
+ "private": (info.get("project") or {}).get("visibility") != "public", "description": None} # fmt: skip
292
+
293
+ def tree(self, branch: str) -> tuple[list[str], bool]:
294
+ data = self._get(f"{self._p}/items", scopePath="/", recursionLevel="Full",
295
+ **{"versionDescriptor.version": branch, "versionDescriptor.versionType": "branch"}) # fmt: skip
296
+ paths = [e["path"].lstrip("/") for e in data.get("value") or [] if not e.get("isFolder")]
297
+ return paths[: self.tuning.max_tree_files], len(paths) <= self.tuning.max_tree_files
298
+
299
+ def read_file(self, path: str) -> str | None:
300
+ resp = self.retrying(f"GET item {path}", lambda: self.rest.call(
301
+ "GET", f"{self._p}/items",
302
+ params={"path": "/" + path, "api-version": API, "versionDescriptor.version": self._branch(),
303
+ "versionDescriptor.versionType": "branch", "includeContent": "true", "$format": "text"},
304
+ headers={"Accept": "text/plain"}, absent=(NotFound,),
305
+ )) # fmt: skip
306
+ return resp.text if resp else None
307
+
308
+ def list_dir(self, path: str) -> list[str]:
309
+ data = self._get_or_none(f"{self._p}/items", scopePath="/" + path, recursionLevel="OneLevel",
310
+ **{"versionDescriptor.version": self._branch()}) or {} # fmt: skip
311
+ return [
312
+ e["path"].rsplit("/", 1)[-1]
313
+ for e in data.get("value") or []
314
+ if not e.get("isFolder") and e["path"].strip("/") != path
315
+ ]
316
+
317
+ # ---- pull requests
318
+
319
+ def fetch_prs(self, limit: int) -> tuple[str, list[PullRequest], int]:
320
+ raw = (
321
+ self._get(f"{self._p}/pullrequests", **{"searchCriteria.status": "active", "$top": limit}).get("value")
322
+ or []
323
+ )
324
+ total = len(raw)
325
+ if len(raw) == limit: # ADO gives no total; count by paging through ids only when the page filled up
326
+ skip, more = limit, True
327
+ while more:
328
+ page = (
329
+ self._get(
330
+ f"{self._p}/pullrequests", **{"searchCriteria.status": "active", "$top": 500, "$skip": skip}
331
+ ).get("value")
332
+ or []
333
+ )
334
+ total += len(page)
335
+ skip += len(page)
336
+ more = len(page) == 500
337
+ raw.sort(key=lambda p: p.get("creationDate") or "", reverse=True)
338
+ self._look_up_history({a for p in raw if (a := (p.get("createdBy") or {}).get("id"))})
339
+ viewer = ""
340
+ if self.rest.cred.token:
341
+ me = self.rest.call("GET", "_apis/connectionData", absent=(ForgeError,)) # organization-scoped
342
+ if me:
343
+ user = (me.json() or {}).get("authenticatedUser") or {}
344
+ viewer = (
345
+ (user.get("properties") or {}).get("Account", {}).get("$value")
346
+ or user.get("providerDisplayName")
347
+ or ""
348
+ )
349
+ return viewer, pool_map(self._complete, raw, self.tuning.concurrency), total
350
+
351
+ # ---- authors
352
+
353
+ def _look_up_history(self, author_ids: set[str]) -> None:
354
+ """Whether each author has had a PR completed in this repo before, one query per author.
355
+
356
+ Azure DevOps has no author association. What it can say is this: everyone who opens a PR holds
357
+ Contribute rights on the repo (GitHub's COLLABORATOR), and the completed-PR history tells a returning
358
+ author from one on their first PR here. Teams and the organization are checked through ``is_member``.
359
+ """
360
+
361
+ def landed(author_id: str) -> tuple[str, Capability[str]]:
362
+ try:
363
+ page = self._get(f"{self._p}/pullrequests", **{"searchCriteria.creatorId": author_id,
364
+ "searchCriteria.status": "completed", "$top": 1}) # fmt: skip
365
+ except ForgeError as exc:
366
+ return author_id, unavailable(f"couldn't read the author's PR history: {exc.reason}")
367
+ return author_id, known("COLLABORATOR" if page.get("value") else "FIRST_TIME_CONTRIBUTOR")
368
+
369
+ wanted = [a for a in author_ids if a not in self._association_of]
370
+ self._association_of.update(pool_map(landed, wanted, self.tuning.concurrency))
371
+
372
+ def _association(self, pr: dict[str, Any]) -> Capability[str]:
373
+ author_id = (pr.get("createdBy") or {}).get("id")
374
+ if author_id is None:
375
+ return unavailable("the PR names no author")
376
+ if author_id not in self._association_of:
377
+ self._look_up_history({author_id})
378
+ return self._association_of[author_id]
379
+
380
+ def is_member(self, group: str, login: str) -> bool:
381
+ """``<organization>``: the author is one of the organization's users. ``<organization or project>/<team>``:
382
+ a member of that team in this repo's project, through any nesting of groups. Only a definite answer
383
+ is returned; a login or team that can't be resolved raises, so the check counts as failed, not as "no"."""
384
+ want = login.lower()
385
+ if group.lower() == self.org.lower():
386
+ return want in self._org_users()
387
+ scope, _, team = group.partition("/")
388
+ if not team or scope.lower() not in (self.org.lower(), self.project.lower()):
389
+ raise ForgeError(
390
+ f"{group!r} isn't this organization or one of its project's teams", what=f"members {group}"
391
+ )
392
+ # The identities API expands a user's containers recursively ("ExpandedUp"), so one call says whether
393
+ # the team is among them, however the team is composed (users, groups, groups of groups).
394
+ ident = self._identities(identityIds=self._identity_id(want), queryMembership="ExpandedUp")
395
+ return self._team_descriptor(team) in ((ident[0].get("memberOf") or []) if ident else [])
396
+
397
+ def _identities(self, **params: Any) -> list[dict[str, Any]]:
398
+ params.setdefault("api-version", API)
399
+ resp = self.retrying("GET identities", lambda: self.vssps.call("GET", "_apis/identities", params=params))
400
+ return ((resp.json() if resp else None) or {}).get("value") or []
401
+
402
+ def _identity_id(self, login: str) -> str:
403
+ """The identity id behind a login: remembered from the PRs fetched this build, else looked up."""
404
+ if login in self._id_of:
405
+ return self._id_of[login]
406
+ for ident in self._identities(searchFilter="General", filterValue=login):
407
+ names = {str(v).lower() for v in (
408
+ ((ident.get("properties") or {}).get("Account") or {}).get("$value"),
409
+ ((ident.get("properties") or {}).get("Mail") or {}).get("$value"),
410
+ ) if v} # fmt: skip
411
+ if login in names and ident.get("id"):
412
+ self._id_of[login] = str(ident["id"])
413
+ return self._id_of[login]
414
+ raise ForgeError(f"no identity found for {login}", what=f"identity {login}")
415
+
416
+ def _team_descriptor(self, team: str) -> str:
417
+ with self._members_lock:
418
+ if team.lower() not in self._team_descriptors:
419
+ teams = self._get(f"_apis/projects/{quote(self.project)}/teams", **{"$top": 500}).get("value") or []
420
+ match = next((t for t in teams if (t.get("name") or "").lower() == team.lower()), None)
421
+ if match is None:
422
+ raise ForgeError(f"no team named {team!r} in {self.project}", what=f"members {team}")
423
+ ident = self._identities(identityIds=match["id"])
424
+ if not ident or not ident[0].get("descriptor"):
425
+ raise ForgeError(f"team {team!r} has no identity descriptor", what=f"members {team}")
426
+ self._team_descriptors[team.lower()] = str(ident[0]["descriptor"])
427
+ return self._team_descriptors[team.lower()]
428
+
429
+ def _org_users(self) -> set[str]:
430
+ with self._members_lock:
431
+ if self._org_logins is None:
432
+ logins: set[str] = set()
433
+ token: str | None = None
434
+ while True:
435
+ params: dict[str, Any] = {"api-version": "7.1-preview.1", "subjectTypes": "aad,msa"}
436
+ if token:
437
+ params["continuationToken"] = token
438
+ resp = self.retrying(
439
+ "GET graph/users", lambda p=params: self.vssps.call("GET", "_apis/graph/users", params=p)
440
+ )
441
+ for user in ((resp.json() if resp else None) or {}).get("value") or []:
442
+ logins |= {str(v).lower() for v in (user.get("principalName"), user.get("mailAddress")) if v}
443
+ token = resp.headers.get("x-ms-continuationtoken") if resp else None
444
+ if not token:
445
+ break
446
+ self._org_logins = logins
447
+ return self._org_logins
448
+
449
+ @staticmethod
450
+ def _merge_commits(pr: dict[str, Any]) -> tuple[str, str] | None:
451
+ """The commits a PR's changes are the difference between: its last merge base and its head."""
452
+ base = (pr.get("lastMergeTargetCommit") or {}).get("commitId")
453
+ head = (pr.get("lastMergeSourceCommit") or {}).get("commitId")
454
+ return (base, head) if base and head else None
455
+
456
+ def _changes(self, base: str, head: str, limit: int) -> tuple[list[dict[str, Any]], bool]:
457
+ """The blob changes between two commits, as Azure DevOps lists them (path, change type, object ids).
458
+
459
+ This is the one changes listing a public project serves without sign-in (iterations need it).
460
+ """
461
+ blobs: list[dict[str, Any]] = []
462
+ skip, complete = 0, True
463
+ while True:
464
+ data = self._get(f"{self._p}/diffs/commits", baseVersion=base, baseVersionType="commit", targetVersion=head,
465
+ targetVersionType="commit", **{"$top": min(1000, limit), "$skip": skip}) # fmt: skip
466
+ changes = data.get("changes") or []
467
+ blobs += [c for c in changes if not (c.get("item") or {}).get("isFolder")
468
+ and (c.get("item") or {}).get("gitObjectType", "blob") == "blob"] # fmt: skip
469
+ if data.get("allChangesIncluded", True) or not changes:
470
+ break
471
+ skip += len(changes)
472
+ if len(blobs) >= limit:
473
+ complete = False
474
+ break
475
+ return blobs[:limit], complete
476
+
477
+ @staticmethod
478
+ def _paths(change: dict[str, Any]) -> tuple[str | None, str | None]:
479
+ """(old path, new path) of a change; a deletion has no new path and an addition no old one."""
480
+ kind = str(change.get("changeType", "")).split(",")[0].strip()
481
+ new = ((change.get("item") or {}).get("path") or "").lstrip("/") or None
482
+ old = (change.get("originalPath") or "").lstrip("/") or None
483
+ if kind == "delete":
484
+ return old or new, None
485
+ if kind == "add":
486
+ return None, new
487
+ return old or new, new
488
+
489
+ def _changed_files(self, pr: dict[str, Any], limit: int) -> tuple[list[ChangedFile], bool]:
490
+ """The paths a PR changes. Azure DevOps reports no line counts anywhere, so additions and deletions stay 0
491
+ here and the record says so; the build counts them from the assembled diff when it has one."""
492
+ commits = self._merge_commits(pr)
493
+ if commits is None:
494
+ return [], True
495
+ changes, complete = self._changes(*commits, limit)
496
+ files = []
497
+ for c in changes:
498
+ kind = str(c.get("changeType", "")).split(",")[0].strip()
499
+ old, new = self._paths(c)
500
+ files.append(ChangedFile(new or old or "", 0, 0, {"add": "ADDED", "delete": "DELETED", "rename": "RENAMED"}.get(kind, "MODIFIED"))) # fmt: skip
501
+ return files, complete
502
+
503
+ def _complete(self, pr: dict[str, Any]) -> PullRequest:
504
+ n = pr["pullRequestId"]
505
+ base = f"{self._p}/pullrequests/{n}"
506
+ if commits := self._merge_commits(pr):
507
+ self._merge_commits_of[n] = commits
508
+ files, complete = self._changed_files(pr, self.tuning.max_files_per_pr)
509
+ truncated = {} if complete else {"files": (len(files), len(files) + 1)}
510
+ reviews = [Review(r.get("uniqueName") or r.get("displayName") or "?", VOTES.get(int(r.get("vote") or 0), "COMMENTED"), None)
511
+ for r in pr.get("reviewers") or [] if not r.get("isContainer")] # fmt: skip
512
+ threads: Capability[list[Thread]]
513
+ last_activity: list[str] = []
514
+ try:
515
+ raw_threads = self._get(f"{base}/threads").get("value") or []
516
+ last_activity += [t["lastUpdatedDate"] for t in raw_threads if t.get("lastUpdatedDate")]
517
+ threads = known([
518
+ Thread((t["comments"][0].get("author") or {}).get("uniqueName") or "?", t["comments"][0].get("content") or "", "",
519
+ ((t.get("threadContext") or {}).get("filePath") or "/").lstrip("/") or None,
520
+ ((t.get("threadContext") or {}).get("rightFileStart") or {}).get("line"),
521
+ t.get("status") in ("fixed", "closed", "wontFix", "byDesign"), False)
522
+ for t in raw_threads if t.get("comments") and t.get("threadContext") and not t.get("isDeleted")
523
+ and t["comments"][0].get("commentType") == "text"
524
+ ]) # fmt: skip
525
+ except ForgeError as exc:
526
+ threads = unavailable(exc.reason)
527
+ head = (pr.get("lastMergeSourceCommit") or {}).get("commitId") or ""
528
+ last_commit = None
529
+ if head:
530
+ commits = (self._get_or_none(f"{base}/commits", **{"$top": 1}) or {}).get("value") or []
531
+ last_commit = (commits[0].get("committer") or {}).get("date") if commits else None
532
+ last_activity += [last_commit] if last_commit else []
533
+ checks: Capability[list[Check]]
534
+ try:
535
+ statuses = self._get_or_none(f"{self._p}/commits/{head}/statuses") if head else None
536
+ checks = known([Check(f"{(s.get('context') or {}).get('genre') or ''}/{(s.get('context') or {}).get('name') or '?'}".strip("/"),
537
+ "COMPLETED" if s.get("state") not in ("pending", "notSet") else "PENDING",
538
+ STATUS.get(s.get("state") or ""), s.get("targetUrl"), s.get("creationDate"))
539
+ for s in (statuses or {}).get("value") or []]) # fmt: skip
540
+ except ForgeError as exc:
541
+ checks = unavailable(exc.reason)
542
+ states = {r.state for r in reviews}
543
+ decision = ("CHANGES_REQUESTED" if "CHANGES_REQUESTED" in states else "APPROVED" if "APPROVED" in states
544
+ else "REVIEW_REQUIRED") # fmt: skip
545
+ merge_status = pr.get("mergeStatus") or "notSet"
546
+ mergeable = (
547
+ "CONFLICTING" if merge_status == "conflicts" else "MERGEABLE" if merge_status == "succeeded" else "UNKNOWN"
548
+ )
549
+ login = self._login(pr)
550
+ return PullRequest(
551
+ number=n, title=pr["title"], url=self.pr_url(n), body=pr.get("description") or "", draft=bool(pr.get("isDraft")),
552
+ created=pr["creationDate"], updated=max([pr["creationDate"], *last_activity]),
553
+ additions=0, deletions=0, changed_files=len(files), head=head,
554
+ base=(pr.get("targetRefName") or "refs/heads/main").removeprefix("refs/heads/"),
555
+ author=Author(login, bot=False), files=files, labels=[label["name"] for label in pr.get("labels") or []],
556
+ requested=[r.get("uniqueName") or r.get("displayName") or "?" for r in pr.get("reviewers") or [] if r.get("isRequired")],
557
+ reviews=reviews, comments=len(threads.value or []) if threads.known else 0,
558
+ last_commit=last_commit, issues=[],
559
+ association=self._association(pr),
560
+ decision=known(decision), mergeable=known(mergeable), threads=threads, checks=checks,
561
+ line_counts=unsupported("Azure DevOps reports no per-file line counts; they are counted from the diff when one is fetched"),
562
+ truncated=truncated,
563
+ ) # fmt: skip
564
+
565
+ def merged_prs(self, count: int) -> tuple[str, list[MergedPullRequest]]:
566
+ raw = (
567
+ self._get(f"{self._p}/pullrequests", **{"searchCriteria.status": "completed", "$top": count}).get("value")
568
+ or []
569
+ )
570
+ self._look_up_history({a for p in raw if (a := (p.get("createdBy") or {}).get("id"))})
571
+ merged = []
572
+ for pr in raw:
573
+ files, _ = self._changed_files(pr, 100)
574
+ merged.append(MergedPullRequest(pr["pullRequestId"], Author(self._login(pr)), self._association(pr), files))
575
+ return self._branch(), merged
576
+
577
+ def _login(self, pr: dict[str, Any]) -> str:
578
+ """The author's login (their unique name, an email on Azure DevOps), remembering which identity it is."""
579
+ author = pr.get("createdBy") or {}
580
+ login = author.get("uniqueName") or author.get("displayName") or "ghost"
581
+ if author.get("id"):
582
+ self._id_of[login.lower()] = str(author["id"])
583
+ return login
584
+
585
+ def fetch_diff(self, number: int) -> str:
586
+ """A unified diff assembled from both versions of each changed file; Azure DevOps serves none itself.
587
+
588
+ Two blob requests per file, so a PR changing more than ``max_assembled_diff_files`` files is treated as
589
+ too large, the way a diff GitHub refuses is: its files still place it on the map, only the line
590
+ heuristics are skipped for it.
591
+ """
592
+ what = f"pr diff #{number}"
593
+ commits = self._merge_commits_of.get(number) or self._merge_commits(
594
+ self._get(f"{self._p}/pullrequests/{number}")
595
+ )
596
+ if commits is None:
597
+ return "" # no merge base yet: nothing to diff against
598
+ cap = self.tuning.max_assembled_diff_files
599
+ changes, complete = self._changes(*commits, cap + 1)
600
+ if not complete or len(changes) > cap:
601
+ raise TooLarge(f"{what}: changes more than {cap} files, the most assembled from blobs", what=what)
602
+
603
+ def blob(object_id: str | None) -> bytes | None:
604
+ if not object_id:
605
+ return None
606
+ resp = self.retrying(f"GET blob {object_id[:12]}", lambda: self.rest.call(
607
+ "GET", f"{self._p}/blobs/{object_id}", params={"api-version": API, "$format": "octetStream"},
608
+ headers={"Accept": "application/octet-stream"},
609
+ )) # fmt: skip
610
+ return resp.content if resp else b""
611
+
612
+ def pair(change: dict[str, Any]) -> FilePair:
613
+ old_path, new_path = self._paths(change)
614
+ item = change.get("item") or {}
615
+ return FilePair(old_path, new_path, blob(item.get("originalObjectId")) if old_path else None,
616
+ blob(item.get("objectId")) if new_path else None) # fmt: skip
617
+
618
+ return assemble_diff(pool_map(pair, changes, self.tuning.concurrency))
619
+
620
+ # ---- CI
621
+
622
+ def ci_context(self, bases: set[str]) -> CiContext:
623
+ branch = self._branch()
624
+ required: dict[str, Capability[set[str]]] = {}
625
+ try:
626
+ if self._repo_id is None:
627
+ self.repo_info()
628
+ data = self._get(f"{quote(self.project)}/_apis/policy/configurations", **{"$top": 500})
629
+ for base in bases:
630
+ names: set[str] = set()
631
+ for cfg in data.get("value") or []:
632
+ if not cfg.get("isEnabled") or (cfg.get("type") or {}).get("displayName") != "Build":
633
+ continue
634
+ for scope in (cfg.get("settings") or {}).get("scope") or []:
635
+ if (
636
+ scope.get("repositoryId") in (None, self._repo_id)
637
+ and (scope.get("refName") or "").removeprefix("refs/heads/") == base
638
+ ):
639
+ names.add(
640
+ (cfg.get("settings") or {}).get("displayName")
641
+ or f"build {(cfg.get('settings') or {}).get('buildDefinitionId')}"
642
+ )
643
+ required[base] = known(names)
644
+ except ForgeError as exc:
645
+ required = {b: unavailable(exc.reason) for b in bases}
646
+ failing: Capability[set[str]]
647
+ try:
648
+ statuses = (
649
+ self._get_or_none(f"{self._p}/commits", **{"searchCriteria.itemVersion.version": branch, "$top": 1})
650
+ or {}
651
+ )
652
+ head = ((statuses.get("value") or [{}])[0]).get("commitId")
653
+ checks = self._get_or_none(f"{self._p}/commits/{head}/statuses") if head else None
654
+ failing = known({f"{(s.get('context') or {}).get('genre') or ''}/{(s.get('context') or {}).get('name') or ''}".strip("/")
655
+ for s in (checks or {}).get("value") or [] if s.get("state") in ("failed", "error")}) # fmt: skip
656
+ except ForgeError as exc:
657
+ failing = unavailable(exc.reason)
658
+ return CiContext(required, failing, branch)