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,487 @@
|
|
|
1
|
+
"""GitHub, through the ``gh`` CLI so your existing sign-in, SSO, and proxy settings are reused.
|
|
2
|
+
|
|
3
|
+
Each repo can name which signed-in ``gh`` account to use (an enterprise-managed account for internal repos,
|
|
4
|
+
a personal one for public repos). The token is passed per call, so your active ``gh`` account never
|
|
5
|
+
changes. PRs come from one GraphQL query per page, with follow-up pages for PRs that have more files,
|
|
6
|
+
review threads, or checks than fit, up to the caps in ``[tuning.forge]``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import re
|
|
14
|
+
import threading
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from readthrough.ci import failing_names
|
|
19
|
+
from readthrough.faults import AuthError, ForgeError, NotFound
|
|
20
|
+
from readthrough.forges import FORGES, CiContext, Forge
|
|
21
|
+
from readthrough.logs import pool_map
|
|
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
|
+
)
|
|
35
|
+
from readthrough.process import Secret, quiet_output, remember, run
|
|
36
|
+
|
|
37
|
+
log = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
REPO_RE = re.compile(r"^[\w.-]+/[\w.-]+$")
|
|
40
|
+
|
|
41
|
+
CHECK_FIELDS = (
|
|
42
|
+
"__typename ... on CheckRun{name conclusion status detailsUrl startedAt completedAt}"
|
|
43
|
+
" ... on StatusContext{context state targetUrl createdAt}"
|
|
44
|
+
)
|
|
45
|
+
FILE_FIELDS = "path additions deletions changeType"
|
|
46
|
+
THREAD_FIELDS = "isResolved isOutdated path line comments(first:2){nodes{author{login} body bodyHTML}}"
|
|
47
|
+
PAGE = "pageInfo{hasNextPage endCursor} totalCount"
|
|
48
|
+
|
|
49
|
+
PR_QUERY = """
|
|
50
|
+
query PullRequests($owner:String!,$name:String!,$cursor:String,$size:Int!){
|
|
51
|
+
viewer{login}
|
|
52
|
+
repository(owner:$owner,name:$name){
|
|
53
|
+
pullRequests(states:OPEN,first:$size,after:$cursor,orderBy:{field:UPDATED_AT,direction:DESC}){
|
|
54
|
+
pageInfo{hasNextPage endCursor} totalCount
|
|
55
|
+
nodes{
|
|
56
|
+
number title url body bodyHTML isDraft createdAt updatedAt additions deletions changedFiles
|
|
57
|
+
headRefOid baseRefName reviewDecision mergeable authorAssociation
|
|
58
|
+
author{__typename login}
|
|
59
|
+
labels(first:10){nodes{name}}
|
|
60
|
+
files(first:100){__PAGE__ nodes{__FILES__}}
|
|
61
|
+
reviewRequests(first:10){nodes{requestedReviewer{... on User{login} ... on Team{name}}}}
|
|
62
|
+
latestReviews(first:20){nodes{author{login} state submittedAt}}
|
|
63
|
+
reviewThreads(first:60){__PAGE__ nodes{__THREADS__}}
|
|
64
|
+
comments{totalCount}
|
|
65
|
+
commits(last:1){nodes{commit{committedDate statusCheckRollup{state contexts(first:100){__PAGE__ nodes{__CHECKS__}}}}}}
|
|
66
|
+
closingIssuesReferences(first:5){nodes{number title url}}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
# Follow-up pages for the PRs that have more than the first page of files, review threads, or checks.
|
|
74
|
+
FILES_QUERY = """
|
|
75
|
+
query PullRequestFiles($owner:String!,$name:String!,$number:Int!,$cursor:String){
|
|
76
|
+
repository(owner:$owner,name:$name){pullRequest(number:$number){files(first:100,after:$cursor){__PAGE__ nodes{__FILES__}}}}
|
|
77
|
+
}
|
|
78
|
+
"""
|
|
79
|
+
THREADS_QUERY = """
|
|
80
|
+
query PullRequestThreads($owner:String!,$name:String!,$number:Int!,$cursor:String){
|
|
81
|
+
repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$cursor){__PAGE__ nodes{__THREADS__}}}}
|
|
82
|
+
}
|
|
83
|
+
"""
|
|
84
|
+
CHECKS_QUERY = """
|
|
85
|
+
query CommitChecks($owner:String!,$name:String!,$oid:GitObjectID!,$cursor:String){
|
|
86
|
+
repository(owner:$owner,name:$name){object(oid:$oid){... on Commit{statusCheckRollup{contexts(first:100,after:$cursor){__PAGE__ nodes{__CHECKS__}}}}}}
|
|
87
|
+
}
|
|
88
|
+
"""
|
|
89
|
+
MAIN_QUERY = """
|
|
90
|
+
query DefaultBranch($owner:String!,$name:String!){
|
|
91
|
+
repository(owner:$owner,name:$name){
|
|
92
|
+
defaultBranchRef{name target{... on Commit{oid statusCheckRollup{state contexts(first:100){__PAGE__ nodes{__CHECKS__}}}}}}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
"""
|
|
96
|
+
MERGED_QUERY = """
|
|
97
|
+
query MergedPullRequests($owner:String!,$name:String!,$count:Int!){
|
|
98
|
+
repository(owner:$owner,name:$name){
|
|
99
|
+
defaultBranchRef{name}
|
|
100
|
+
pullRequests(states:MERGED,last:$count,orderBy:{field:UPDATED_AT,direction:ASC}){
|
|
101
|
+
nodes{number author{login __typename} authorAssociation files(first:100){nodes{path additions deletions}}}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _fill(query: str) -> str:
|
|
109
|
+
return (query.replace("__PAGE__", PAGE).replace("__FILES__", FILE_FIELDS)
|
|
110
|
+
.replace("__THREADS__", THREAD_FIELDS).replace("__CHECKS__", CHECK_FIELDS)) # fmt: skip
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
PR_QUERY, FILES_QUERY, THREADS_QUERY, CHECKS_QUERY, MAIN_QUERY = map(
|
|
114
|
+
_fill, (PR_QUERY, FILES_QUERY, THREADS_QUERY, CHECKS_QUERY, MAIN_QUERY)
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------- accounts
|
|
119
|
+
|
|
120
|
+
_tokens: dict[str, Secret] = {}
|
|
121
|
+
_tokens_lock = threading.Lock()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def token_for(account: str) -> Secret:
|
|
125
|
+
"""The stored token for a signed-in ``gh`` account (``gh auth token --user``). Cached per process."""
|
|
126
|
+
with _tokens_lock:
|
|
127
|
+
if account not in _tokens:
|
|
128
|
+
out = quiet_output(["gh", "auth", "token", "--user", account])
|
|
129
|
+
if not out or not out.strip():
|
|
130
|
+
raise ForgeError(f"gh isn't signed in as {account}. Run: gh auth login (then pick that account)")
|
|
131
|
+
_tokens[account] = remember(Secret(out.strip()))
|
|
132
|
+
return _tokens[account]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def signed_in_accounts() -> list[str]:
|
|
136
|
+
out = quiet_output(["gh", "auth", "status"])
|
|
137
|
+
found: list[str] = []
|
|
138
|
+
for line in (out or "").splitlines():
|
|
139
|
+
if "Logged in to github.com account" in line:
|
|
140
|
+
name = line.split("account", 1)[1].split()[0]
|
|
141
|
+
if name not in found:
|
|
142
|
+
found.append(name)
|
|
143
|
+
return found
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ---------------------------------------------------------------- the adapter
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True)
|
|
150
|
+
class GitHubOptions:
|
|
151
|
+
host: str = "github.com" # a GitHub Enterprise Server host goes here; gh must be signed in to it
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@FORGES.add("github", "GitHub and GitHub Enterprise, through the gh CLI", options=GitHubOptions)
|
|
155
|
+
class GitHub(Forge):
|
|
156
|
+
name = "github"
|
|
157
|
+
label = "GitHub"
|
|
158
|
+
config_dir = ".github"
|
|
159
|
+
capabilities = frozenset({"diffs", "required_checks", "default_branch_ci", "rate_limit", "memberships", "accounts"})
|
|
160
|
+
access = "the gh CLI (its GraphQL and REST calls), which carries your sign-in, SSO, and proxies"
|
|
161
|
+
credentials = ("the gh account you pick here, else gh's active account",)
|
|
162
|
+
|
|
163
|
+
def __init__(self, repo: str, options: Any = None, tuning: Any = None, *, account: str | None = None) -> None:
|
|
164
|
+
super().__init__(repo, options or GitHubOptions(), tuning, account=account)
|
|
165
|
+
self.owner, self.repo_name = repo.split("/")
|
|
166
|
+
self.host: str = getattr(self.options, "host", "github.com")
|
|
167
|
+
|
|
168
|
+
@classmethod
|
|
169
|
+
def validate_repo(cls, repo: str) -> str | None:
|
|
170
|
+
if not REPO_RE.match(repo):
|
|
171
|
+
return f"{repo!r} isn't owner/name"
|
|
172
|
+
return cls.bad_segment(repo.split("/"))
|
|
173
|
+
|
|
174
|
+
def web_url(self) -> str:
|
|
175
|
+
return f"https://{self.host}/{self.repo}"
|
|
176
|
+
|
|
177
|
+
def pr_url(self, number: int) -> str:
|
|
178
|
+
return f"{self.web_url()}/pull/{number}"
|
|
179
|
+
|
|
180
|
+
def pr_ref(self, number: int) -> str:
|
|
181
|
+
return f"pull/{number}/head"
|
|
182
|
+
|
|
183
|
+
def file_url(self, path: str, branch: str) -> str:
|
|
184
|
+
return f"{self.web_url()}/blob/{branch}/{path}"
|
|
185
|
+
|
|
186
|
+
def new_file_url(self, path: str, branch: str) -> str | None:
|
|
187
|
+
from urllib.parse import quote
|
|
188
|
+
|
|
189
|
+
return f"{self.web_url()}/new/{quote(branch, safe='')}?filename={quote(path)}"
|
|
190
|
+
|
|
191
|
+
def describe_auth(self) -> str:
|
|
192
|
+
return f"gh as {self.account}" if self.account else "gh (active account)"
|
|
193
|
+
|
|
194
|
+
# ---- gh calls
|
|
195
|
+
|
|
196
|
+
def run(self, cmd: list[str], *, check: bool = True) -> str:
|
|
197
|
+
"""Run ``gh`` as this repo's account. Temporary failures are retried with backoff."""
|
|
198
|
+
env = {"GH_TOKEN": token_for(self.account).reveal()} if self.account and cmd[:1] == ["gh"] else None
|
|
199
|
+
if self.host != "github.com" and cmd[:1] == ["gh"]:
|
|
200
|
+
env = {**(env or {}), "GH_HOST": self.host}
|
|
201
|
+
return self.retrying(
|
|
202
|
+
" ".join(cmd[:3]), lambda: run(cmd, check=check, env=env, timeout=self.tuning.timeout_seconds)
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
def api(self, path: str) -> str:
|
|
206
|
+
return self.run(["gh", "api", path])
|
|
207
|
+
|
|
208
|
+
def api_or_none(self, path: str, *, absent: tuple[type[ForgeError], ...] = (NotFound,)) -> str | None:
|
|
209
|
+
"""``None`` only when GitHub says the thing isn't there. Network and other failures still raise."""
|
|
210
|
+
try:
|
|
211
|
+
return self.api(path)
|
|
212
|
+
except absent:
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
def raw(self, path: str) -> str:
|
|
216
|
+
return self.run(["gh", "api", "-H", "Accept: application/vnd.github.raw", f"repos/{self.repo}/contents/{path}"])
|
|
217
|
+
|
|
218
|
+
def graphql(self, query: str, **variables: str | int) -> dict[str, Any]:
|
|
219
|
+
cmd = ["gh", "api", "graphql", "-f", f"query={query}"]
|
|
220
|
+
for key, value in variables.items():
|
|
221
|
+
# -F makes gh guess the type ("123" becomes a number), so only real integers use it.
|
|
222
|
+
cmd += ["-F" if isinstance(value, int) else "-f", f"{key}={value}"]
|
|
223
|
+
data = json.loads(self.run(cmd))
|
|
224
|
+
if data.get("errors") and not data.get("data"):
|
|
225
|
+
raise ForgeError(f"graphql: {data['errors'][0].get('message', data['errors'])}", what="graphql")
|
|
226
|
+
return data["data"]
|
|
227
|
+
|
|
228
|
+
# ---- the repo
|
|
229
|
+
|
|
230
|
+
def repo_info(self) -> dict[str, Any]:
|
|
231
|
+
info = json.loads(self.api(f"repos/{self.repo}"))
|
|
232
|
+
return {k: info.get(k) for k in ("full_name", "default_branch", "private", "description")}
|
|
233
|
+
|
|
234
|
+
def rate_limit(self) -> dict[str, int] | None:
|
|
235
|
+
"""Remaining REST and GraphQL calls (checking doesn't count against the limit)."""
|
|
236
|
+
try:
|
|
237
|
+
res = json.loads(self.api("rate_limit"))["resources"]
|
|
238
|
+
except (ForgeError, ValueError, KeyError):
|
|
239
|
+
return None
|
|
240
|
+
return {"rest": res["core"]["remaining"], "graphql": res["graphql"]["remaining"]}
|
|
241
|
+
|
|
242
|
+
def tree(self, branch: str) -> tuple[list[str], bool]:
|
|
243
|
+
# One call for the whole tree, so max_tree_files doesn't apply; GitHub itself truncates past ~100,000 entries.
|
|
244
|
+
data = json.loads(self.api(f"repos/{self.repo}/git/trees/{branch}?recursive=1"))
|
|
245
|
+
return [e["path"] for e in data.get("tree", []) if e.get("type") == "blob"], not data.get("truncated")
|
|
246
|
+
|
|
247
|
+
def read_file(self, path: str) -> str | None:
|
|
248
|
+
try:
|
|
249
|
+
return self.raw(path)
|
|
250
|
+
except NotFound:
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
def read_files(self, paths: list[str]) -> dict[str, str]:
|
|
254
|
+
"""Several files in one GraphQL call; a null object is a real "doesn't exist", an error still raises."""
|
|
255
|
+
if not paths:
|
|
256
|
+
return {}
|
|
257
|
+
fields = " ".join(f'f{i}: object(expression:"HEAD:{p}"){{... on Blob{{text}}}}' for i, p in enumerate(paths))
|
|
258
|
+
query = f"query Files($owner:String!,$name:String!){{repository(owner:$owner,name:$name){{{fields}}}}}"
|
|
259
|
+
repo = self.graphql(query, owner=self.owner, name=self.repo_name)["repository"]
|
|
260
|
+
return {
|
|
261
|
+
p: repo[f"f{i}"]["text"]
|
|
262
|
+
for i, p in enumerate(paths)
|
|
263
|
+
if repo.get(f"f{i}") and repo[f"f{i}"].get("text") is not None
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
def list_dir(self, path: str) -> list[str]:
|
|
267
|
+
out = self.api_or_none(f"repos/{self.repo}/contents/{path}")
|
|
268
|
+
listing = json.loads(out) if out and out.strip().startswith("[") else []
|
|
269
|
+
return [e["name"] for e in listing if e.get("type") == "file"]
|
|
270
|
+
|
|
271
|
+
def is_member(self, group: str, login: str) -> bool:
|
|
272
|
+
"""Is ``login`` in the org (``"org"``) or team (``"org/team-slug"``)? Only a 404 means no; other failures raise."""
|
|
273
|
+
org, _, team = group.partition("/")
|
|
274
|
+
try:
|
|
275
|
+
if not team:
|
|
276
|
+
self.api(f"orgs/{org}/members/{login}") # 204 if a member visible to you, else 404
|
|
277
|
+
return True
|
|
278
|
+
out = self.api(f"orgs/{org}/teams/{team}/memberships/{login}")
|
|
279
|
+
return json.loads(out or "{}").get("state") == "active"
|
|
280
|
+
except NotFound:
|
|
281
|
+
return False
|
|
282
|
+
|
|
283
|
+
# ---- PRs
|
|
284
|
+
|
|
285
|
+
def fetch_prs(self, limit: int) -> tuple[str, list[PullRequest], int]:
|
|
286
|
+
prs: list[dict[str, Any]] = []
|
|
287
|
+
cursor: str | None = None
|
|
288
|
+
viewer, total = "", 0
|
|
289
|
+
while len(prs) < limit:
|
|
290
|
+
extra: dict[str, str | int] = {"cursor": cursor} if cursor else {}
|
|
291
|
+
size = min(self.tuning.pr_page_size, limit - len(prs))
|
|
292
|
+
data = self.graphql(PR_QUERY, owner=self.owner, name=self.repo_name, size=size, **extra)
|
|
293
|
+
viewer = data["viewer"]["login"]
|
|
294
|
+
page = data["repository"]["pullRequests"]
|
|
295
|
+
total = page["totalCount"]
|
|
296
|
+
prs.extend(page["nodes"])
|
|
297
|
+
log.info("fetched %d of %d open PRs", len(prs), total)
|
|
298
|
+
if not page["pageInfo"]["hasNextPage"]:
|
|
299
|
+
break
|
|
300
|
+
cursor = page["pageInfo"]["endCursor"]
|
|
301
|
+
prs = prs[:limit]
|
|
302
|
+
pool_map(self.complete_pr, [p for p in prs if _needs_more(p)], self.tuning.concurrency)
|
|
303
|
+
return viewer, [normalize(p) for p in prs], total
|
|
304
|
+
|
|
305
|
+
def complete_pr(self, pr: dict[str, Any]) -> None:
|
|
306
|
+
"""Fetch the rest of a PR's files, review threads, and checks, up to the configured caps.
|
|
307
|
+
|
|
308
|
+
Whatever is still cut off is recorded under ``pr["truncated"]`` so the dashboard can say so.
|
|
309
|
+
"""
|
|
310
|
+
n = pr["number"]
|
|
311
|
+
caps = {"files": self.tuning.max_files_per_pr, "reviewThreads": self.tuning.max_review_threads_per_pr}
|
|
312
|
+
for field, query in (("files", FILES_QUERY), ("reviewThreads", THREADS_QUERY)):
|
|
313
|
+
conn = pr[field]
|
|
314
|
+
self._follow(conn, caps[field], lambda c, q=query, f=field: self.graphql(
|
|
315
|
+
q, owner=self.owner, name=self.repo_name, number=n, cursor=c)["repository"]["pullRequest"][f]) # fmt: skip
|
|
316
|
+
commit = (pr["commits"]["nodes"] or [{}])[0].get("commit") or {}
|
|
317
|
+
rollup = commit.get("statusCheckRollup") or {}
|
|
318
|
+
if rollup.get("contexts"):
|
|
319
|
+
self._follow(rollup["contexts"], self.tuning.max_checks_per_pr, lambda c: self.graphql(
|
|
320
|
+
CHECKS_QUERY, owner=self.owner, name=self.repo_name, oid=pr["headRefOid"], cursor=c,
|
|
321
|
+
)["repository"]["object"]["statusCheckRollup"]["contexts"]) # fmt: skip
|
|
322
|
+
truncated = {
|
|
323
|
+
name: [len(conn["nodes"]), conn["totalCount"]]
|
|
324
|
+
for name, conn in (("files", pr["files"]), ("review threads", pr["reviewThreads"]), ("checks", rollup.get("contexts")))
|
|
325
|
+
if conn and conn.get("totalCount", 0) > len(conn["nodes"])
|
|
326
|
+
} # fmt: skip
|
|
327
|
+
if truncated:
|
|
328
|
+
pr["truncated"] = truncated
|
|
329
|
+
|
|
330
|
+
@staticmethod
|
|
331
|
+
def _follow(conn: dict[str, Any], cap: int, fetch: Any) -> None:
|
|
332
|
+
while conn["pageInfo"]["hasNextPage"] and len(conn["nodes"]) < cap:
|
|
333
|
+
page = fetch(conn["pageInfo"]["endCursor"])
|
|
334
|
+
conn["nodes"].extend(page["nodes"])
|
|
335
|
+
conn["pageInfo"] = page["pageInfo"]
|
|
336
|
+
del conn["nodes"][cap:]
|
|
337
|
+
|
|
338
|
+
def merged_prs(self, count: int) -> tuple[str, list[MergedPullRequest]]:
|
|
339
|
+
data = self.graphql(MERGED_QUERY, owner=self.owner, name=self.repo_name, count=count)["repository"]
|
|
340
|
+
branch = (data.get("defaultBranchRef") or {}).get("name") or "main"
|
|
341
|
+
merged = [
|
|
342
|
+
MergedPullRequest(
|
|
343
|
+
number=pr["number"],
|
|
344
|
+
author=_author(pr.get("author")),
|
|
345
|
+
association=known(pr.get("authorAssociation") or "NONE"),
|
|
346
|
+
files=[ChangedFile(f["path"], f["additions"], f["deletions"]) for f in pr["files"]["nodes"]],
|
|
347
|
+
)
|
|
348
|
+
for pr in data["pullRequests"]["nodes"]
|
|
349
|
+
]
|
|
350
|
+
return branch, merged
|
|
351
|
+
|
|
352
|
+
def fetch_diff(self, number: int) -> str:
|
|
353
|
+
return self.run(["gh", "pr", "diff", str(number), "-R", self.repo])
|
|
354
|
+
|
|
355
|
+
# ---- CI
|
|
356
|
+
|
|
357
|
+
def required_checks(self, branch: str) -> Capability[set[str]]:
|
|
358
|
+
"""Required status checks for a branch, from classic protection and rulesets."""
|
|
359
|
+
names: set[str] = set()
|
|
360
|
+
seen_any = False
|
|
361
|
+
refused: list[str] = []
|
|
362
|
+
|
|
363
|
+
# The two sources are a union: a source this account may not read leaves the set incomplete, which is not
|
|
364
|
+
# the same as that source having nothing (a 404).
|
|
365
|
+
def read(path: str) -> Any:
|
|
366
|
+
try:
|
|
367
|
+
return self.api_or_none(path, absent=(NotFound,))
|
|
368
|
+
except AuthError as exc:
|
|
369
|
+
refused.append(exc.reason)
|
|
370
|
+
return None
|
|
371
|
+
|
|
372
|
+
try:
|
|
373
|
+
out = read(f"repos/{self.repo}/branches/{branch}")
|
|
374
|
+
if out:
|
|
375
|
+
seen_any = True
|
|
376
|
+
protection = (json.loads(out).get("protection") or {}).get("required_status_checks") or {}
|
|
377
|
+
names.update(protection.get("contexts") or [])
|
|
378
|
+
names.update(c["context"] for c in protection.get("checks") or [] if c.get("context"))
|
|
379
|
+
out = read(f"repos/{self.repo}/rules/branches/{branch}")
|
|
380
|
+
if out:
|
|
381
|
+
seen_any = True
|
|
382
|
+
for rule in json.loads(out):
|
|
383
|
+
if rule.get("type") == "required_status_checks":
|
|
384
|
+
params = rule.get("parameters") or {}
|
|
385
|
+
names.update(
|
|
386
|
+
c["context"] for c in params.get("required_status_checks") or [] if c.get("context")
|
|
387
|
+
)
|
|
388
|
+
except ForgeError as exc:
|
|
389
|
+
return unavailable(exc.reason)
|
|
390
|
+
if refused:
|
|
391
|
+
what = "fully visible" if seen_any else "visible"
|
|
392
|
+
return unavailable(f"branch protection isn't {what} to this account: {refused[0]}")
|
|
393
|
+
return known(names) if seen_any else unavailable("branch protection isn't visible to this account")
|
|
394
|
+
|
|
395
|
+
def ci_context(self, bases: set[str]) -> CiContext:
|
|
396
|
+
data = self.graphql(MAIN_QUERY, owner=self.owner, name=self.repo_name)
|
|
397
|
+
ref = data["repository"]["defaultBranchRef"] or {}
|
|
398
|
+
target = ref.get("target") or {}
|
|
399
|
+
rollup = target.get("statusCheckRollup") or {}
|
|
400
|
+
if rollup.get("contexts") and target.get("oid"):
|
|
401
|
+
self._follow(rollup["contexts"], self.tuning.max_checks_per_pr, lambda c: self.graphql(
|
|
402
|
+
CHECKS_QUERY, owner=self.owner, name=self.repo_name, oid=target["oid"], cursor=c,
|
|
403
|
+
)["repository"]["object"]["statusCheckRollup"]["contexts"]) # fmt: skip
|
|
404
|
+
|
|
405
|
+
main_failing = failing_names(_checks((rollup.get("contexts") or {}).get("nodes") or []))
|
|
406
|
+
ordered = sorted(bases)
|
|
407
|
+
required = dict(zip(ordered, pool_map(self.required_checks, ordered, self.tuning.concurrency), strict=True))
|
|
408
|
+
return CiContext(required, known(main_failing), ref.get("name") or "main")
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
# ---------------------------------------------------------------- GraphQL -> model
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _needs_more(pr: dict[str, Any]) -> bool:
|
|
415
|
+
commit = (pr["commits"]["nodes"] or [{}])[0].get("commit") or {}
|
|
416
|
+
contexts = (commit.get("statusCheckRollup") or {}).get("contexts") or {}
|
|
417
|
+
return any(
|
|
418
|
+
(conn or {}).get("pageInfo", {}).get("hasNextPage") for conn in (pr["files"], pr["reviewThreads"], contexts)
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _author(raw: dict[str, Any] | None) -> Author:
|
|
423
|
+
raw = raw or {}
|
|
424
|
+
return Author(raw.get("login") or "ghost", bot=raw.get("__typename") == "Bot")
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _checks(nodes: list[dict[str, Any]]) -> list[Check]:
|
|
428
|
+
out = []
|
|
429
|
+
for n in nodes:
|
|
430
|
+
if n.get("__typename") == "StatusContext":
|
|
431
|
+
state = n.get("state") or "PENDING"
|
|
432
|
+
done = state in ("SUCCESS", "FAILURE", "ERROR")
|
|
433
|
+
out.append(Check(n.get("context") or "?", "COMPLETED" if done else "PENDING", state if done else None,
|
|
434
|
+
n.get("targetUrl"), n.get("createdAt"))) # fmt: skip
|
|
435
|
+
else:
|
|
436
|
+
out.append(Check(n.get("name") or "?", n.get("status") or "QUEUED", n.get("conclusion"), n.get("detailsUrl"),
|
|
437
|
+
n.get("startedAt"), n.get("completedAt"))) # fmt: skip
|
|
438
|
+
return out
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def normalize(pr: dict[str, Any]) -> PullRequest:
|
|
442
|
+
"""One PR from the GraphQL query (after any follow-up pages) as the neutral record."""
|
|
443
|
+
commit = (pr["commits"]["nodes"] or [{}])[0].get("commit") or {}
|
|
444
|
+
rollup = commit.get("statusCheckRollup")
|
|
445
|
+
requested = [
|
|
446
|
+
(r.get("requestedReviewer") or {}).get("login") or (r.get("requestedReviewer") or {}).get("name")
|
|
447
|
+
for r in pr["reviewRequests"]["nodes"]
|
|
448
|
+
]
|
|
449
|
+
threads = [
|
|
450
|
+
Thread(
|
|
451
|
+
author=((t["comments"]["nodes"] or [{}])[0].get("author") or {}).get("login") or "ghost",
|
|
452
|
+
body=(t["comments"]["nodes"] or [{}])[0].get("body") or "",
|
|
453
|
+
body_html=(t["comments"]["nodes"] or [{}])[0].get("bodyHTML") or "",
|
|
454
|
+
path=t.get("path"), line=t.get("line"), resolved=bool(t.get("isResolved")), outdated=bool(t.get("isOutdated")),
|
|
455
|
+
)
|
|
456
|
+
for t in pr["reviewThreads"]["nodes"]
|
|
457
|
+
] # fmt: skip
|
|
458
|
+
return PullRequest(
|
|
459
|
+
number=pr["number"],
|
|
460
|
+
title=pr["title"],
|
|
461
|
+
url=pr["url"],
|
|
462
|
+
body=pr.get("body") or "",
|
|
463
|
+
body_html=pr.get("bodyHTML") or "",
|
|
464
|
+
draft=bool(pr["isDraft"]),
|
|
465
|
+
created=pr["createdAt"],
|
|
466
|
+
updated=pr["updatedAt"],
|
|
467
|
+
additions=pr["additions"],
|
|
468
|
+
deletions=pr["deletions"],
|
|
469
|
+
changed_files=pr["changedFiles"],
|
|
470
|
+
head=pr["headRefOid"],
|
|
471
|
+
base=pr["baseRefName"],
|
|
472
|
+
author=_author(pr.get("author")),
|
|
473
|
+
files=[ChangedFile(f["path"], f["additions"], f["deletions"], f.get("changeType") or "MODIFIED") for f in pr["files"]["nodes"]],
|
|
474
|
+
labels=[label["name"] for label in pr["labels"]["nodes"]],
|
|
475
|
+
requested=[r for r in requested if r],
|
|
476
|
+
reviews=[Review(r["author"]["login"], r["state"], r.get("submittedAt")) for r in pr["latestReviews"]["nodes"] if r.get("author")],
|
|
477
|
+
comments=pr["comments"]["totalCount"],
|
|
478
|
+
last_commit=commit.get("committedDate"),
|
|
479
|
+
issues=[Issue(i["number"], i["title"], i["url"]) for i in pr["closingIssuesReferences"]["nodes"]],
|
|
480
|
+
association=known(pr.get("authorAssociation") or "NONE"),
|
|
481
|
+
decision=known(pr.get("reviewDecision") or "NONE"),
|
|
482
|
+
mergeable=known(pr.get("mergeable") or "UNKNOWN"),
|
|
483
|
+
threads=known(threads),
|
|
484
|
+
# A commit with no rollup has no checks at all: that's a known empty, which `ci.classify` calls "not run".
|
|
485
|
+
checks=known(_checks(((rollup or {}).get("contexts") or {}).get("nodes") or [])),
|
|
486
|
+
truncated={k: (v[0], v[1]) for k, v in (pr.get("truncated") or {}).items()},
|
|
487
|
+
) # fmt: skip
|