eddieland-canopy-github 0.14.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.
- canopy_github/__init__.py +504 -0
- canopy_github/connect.py +267 -0
- canopy_github/issues.py +682 -0
- canopy_github/post.py +866 -0
- canopy_github/read.py +656 -0
- canopy_github/repository.py +91 -0
- eddieland_canopy_github-0.14.0.dist-info/METADATA +115 -0
- eddieland_canopy_github-0.14.0.dist-info/RECORD +10 -0
- eddieland_canopy_github-0.14.0.dist-info/WHEEL +4 -0
- eddieland_canopy_github-0.14.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
"""canopy's GitHub programs (DESIGN §29): `canopy-connect-github` reads, `canopy-post-github` writes.
|
|
2
|
+
|
|
3
|
+
canopy runs them as commands, never imports them, so the harness holds no token and opens no connection (TRUST_MODEL
|
|
4
|
+
T2, D003). Each reads the token `gh` holds for the host its PR's URL or repository's clone URL names, when it runs,
|
|
5
|
+
and talks to that host's GraphQL API, so GitHub Enterprise works as github.com does. This module holds what both
|
|
6
|
+
share: reading a PR's or an issue's URL and a clone URL, the token, the GraphQL client, and the JSON lines they print.
|
|
7
|
+
|
|
8
|
+
click for the command lines (D025), canopy-http for every request (D130), and nothing from canopy.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from datetime import UTC, datetime
|
|
19
|
+
from typing import Final, TextIO
|
|
20
|
+
|
|
21
|
+
import canopy_http
|
|
22
|
+
|
|
23
|
+
#: How long `gh` may take to name the hosts it is logged in to, or a token.
|
|
24
|
+
TIMEOUT_SECONDS: Final = 30
|
|
25
|
+
#: The media type that names the preview a PR's `mergeStateStatus` was introduced under.
|
|
26
|
+
MERGE_INFO_PREVIEW: Final = "application/vnd.github.merge-info-preview+json"
|
|
27
|
+
#: How much of a comment's or review's body is printed. canopy bounds what it records again.
|
|
28
|
+
MAX_BODY: Final = 8000
|
|
29
|
+
#: How long a query GitHub answered with a server error, such as its unicorn page, or whose reply was cut off, or that
|
|
30
|
+
#: GitHub failed to run, waits before each new try, give or take half at random: one try, then one more for each
|
|
31
|
+
#: pause. A mutation is sent again only when it never left or GitHub refused it for its rate limit, as one GitHub failed
|
|
32
|
+
#: to answer may have been carried out (canopy-http).
|
|
33
|
+
RETRY_PAUSES: Final[Sequence[float]] = (1.0, 3.0)
|
|
34
|
+
#: How much of GitHub's reply an error quotes.
|
|
35
|
+
_MAX_REPLY: Final = 500
|
|
36
|
+
#: How GitHub's GraphQL API starts the error it answers a query it failed to run with, most often one that ran past
|
|
37
|
+
#: its time limit, though it answers with a 200. The rest names when, and the request ID GitHub's support asks for.
|
|
38
|
+
_FAILED_TO_RUN: Final = "Something went wrong while executing your query"
|
|
39
|
+
#: A query, which reads and so may be sent again, as a mutation may not: the operation each document names first.
|
|
40
|
+
_QUERY: Final = re.compile(r"\s*query\b")
|
|
41
|
+
_HOST: Final = r"[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?(?::[0-9]{1,5})?"
|
|
42
|
+
_NAME: Final = r"[A-Za-z0-9_.-]{1,100}"
|
|
43
|
+
_NUMBER: Final = r"[1-9][0-9]{0,9}"
|
|
44
|
+
_PR: Final = re.compile(rf"https://({_HOST})/({_NAME})/({_NAME})/pull/({_NUMBER})")
|
|
45
|
+
_ISSUE: Final = re.compile(rf"https://({_HOST})/({_NAME})/({_NAME})/issues/({_NUMBER})")
|
|
46
|
+
#: A clone URL as `git clone` takes it: https, scp-style SSH, or ssh://, with an optional `.git` and trailing slash. An
|
|
47
|
+
#: SSH URL's port is the SSH server's, not the API's, so it is not part of the host.
|
|
48
|
+
_HOST_NAME: Final = r"[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?"
|
|
49
|
+
_CLONE: Final = re.compile(
|
|
50
|
+
rf"(?:https://({_HOST})/|ssh://git@({_HOST_NAME})(?::[0-9]{{1,5}})?/|git@({_HOST_NAME}):)"
|
|
51
|
+
rf"({_NAME})/({_NAME}?)(?:\.git)?/?",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
#: The host a token is for, to the GraphQL endpoint to send it to; and the host to the token.
|
|
55
|
+
type Endpoint = Callable[[str], str]
|
|
56
|
+
type Token = Callable[[str], str]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class InputError(Exception):
|
|
60
|
+
"""What the program was given cannot be used, so it did nothing. Exit 2."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class GitHubError(Exception):
|
|
64
|
+
"""GitHub refused a request, or could not be reached.
|
|
65
|
+
|
|
66
|
+
`certain` is whether GitHub is known not to have carried out the request: a reply that refused it, or a request that
|
|
67
|
+
never left. A request that timed out, broke off, or got a server error may have been carried out.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(self, message: str, *, certain: bool, types: tuple[str, ...] = ()) -> None:
|
|
71
|
+
"""Make the error; `certain` as the class says, `types` the GraphQL errors' types, such as `NOT_FOUND`."""
|
|
72
|
+
super().__init__(message)
|
|
73
|
+
self.certain = certain
|
|
74
|
+
self.types = types
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ServerError(GitHubError):
|
|
78
|
+
"""GitHub answered with a server error, as when it shows its unicorn, or with what is not JSON, or broke off.
|
|
79
|
+
|
|
80
|
+
It may have carried the request out, so it is never `certain`. A query too heavy to answer in time gets one, whether
|
|
81
|
+
as a 502 or as the error GitHub's GraphQL API answers a query it failed to run with, and so does one whose
|
|
82
|
+
connection was reset, closed, or cut off before its reply came whole.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class Ref:
|
|
88
|
+
"""A PR or an issue, as its URL names it."""
|
|
89
|
+
|
|
90
|
+
url: str
|
|
91
|
+
host: str
|
|
92
|
+
owner: str
|
|
93
|
+
name: str
|
|
94
|
+
number: int
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class Repository:
|
|
99
|
+
"""A repository canopy names, and where its clone URL says it is on GitHub."""
|
|
100
|
+
|
|
101
|
+
#: canopy's name for it, which its `branch` lines carry.
|
|
102
|
+
name: str
|
|
103
|
+
host: str
|
|
104
|
+
owner: str
|
|
105
|
+
repo: str
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def parse_repository(name: str, url: object) -> Repository:
|
|
109
|
+
"""Read where a repository is from its clone URL: `https://HOST/OWNER/REPO`, `git@HOST:OWNER/REPO`, or `ssh://`.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
The repository.
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
InputError: `url` is not such a URL.
|
|
116
|
+
"""
|
|
117
|
+
match = _CLONE.fullmatch(url) if isinstance(url, str) else None
|
|
118
|
+
if match is None or match[5] in {".", ".."}:
|
|
119
|
+
raise InputError(f"its clone URL {url!r} names no repository on a GitHub host")
|
|
120
|
+
host = next(h for h in match.groups()[:3] if h is not None)
|
|
121
|
+
return Repository(name=name, host=host.lower(), owner=match[4], repo=match[5])
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def parse_pr(url: object) -> Ref:
|
|
125
|
+
"""Read a PR's URL, `https://HOST/OWNER/REPO/pull/N`.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
The PR it names.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
InputError: `url` is not such a URL.
|
|
132
|
+
"""
|
|
133
|
+
return _parse(_PR, url, "a PR's URL, https://HOST/OWNER/REPO/pull/N")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def parse_issue(url: object) -> Ref:
|
|
137
|
+
"""Read an issue's URL, `https://HOST/OWNER/REPO/issues/N`.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
The issue it names.
|
|
141
|
+
|
|
142
|
+
Raises:
|
|
143
|
+
InputError: `url` is not such a URL.
|
|
144
|
+
"""
|
|
145
|
+
return _parse(_ISSUE, url, "an issue's URL, https://HOST/OWNER/REPO/issues/N")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _parse(pattern: re.Pattern[str], url: object, what: str) -> Ref:
|
|
149
|
+
match = pattern.fullmatch(url) if isinstance(url, str) else None
|
|
150
|
+
if match is None:
|
|
151
|
+
raise InputError(f"{url!r} is not {what}")
|
|
152
|
+
host, owner, name, number = match.groups()
|
|
153
|
+
return Ref(url=match.group(0), host=host.lower(), owner=owner, name=name, number=int(number))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def endpoint(host: str) -> str:
|
|
157
|
+
"""The GraphQL endpoint for `host`: github.com's API host, or an Enterprise server's own `/api/graphql`.
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
The endpoint's URL.
|
|
161
|
+
"""
|
|
162
|
+
return "https://api.github.com/graphql" if host == "github.com" else f"https://{host}/api/graphql"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def gh_token(host: str) -> str:
|
|
166
|
+
"""The token `gh` holds for `host`, read now, once `gh` names `host` as one it is logged in to. It is never printed.
|
|
167
|
+
|
|
168
|
+
`gh auth token` alone is not enough: with `GH_ENTERPRISE_TOKEN` set, it answers that token for any host but
|
|
169
|
+
github.com, so a PR's URL naming a host of its writer's choosing would be sent it (TRUST_MODEL T2).
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
The token.
|
|
173
|
+
|
|
174
|
+
Raises:
|
|
175
|
+
InputError: `gh` is not installed, is not logged in to `host`, or holds no token for it.
|
|
176
|
+
"""
|
|
177
|
+
status = _gh(["auth", "status", "--json", "hosts", "--hostname", host], host)
|
|
178
|
+
try:
|
|
179
|
+
hosts: object = json.loads(status.stdout).get("hosts")
|
|
180
|
+
except (json.JSONDecodeError, AttributeError) as e:
|
|
181
|
+
raise InputError(f"cannot read the hosts gh is logged in to: {status.stderr.strip()[:_MAX_REPLY]}") from e
|
|
182
|
+
if status.returncode != 0 or not isinstance(hosts, dict) or host not in hosts:
|
|
183
|
+
raise InputError(f"gh is not logged in to {host}; run: gh auth login --hostname {host}")
|
|
184
|
+
done = _gh(["auth", "token", "--hostname", host], host)
|
|
185
|
+
token = done.stdout.strip()
|
|
186
|
+
if done.returncode != 0 or not token or any(c.isspace() or not c.isprintable() for c in token):
|
|
187
|
+
raise InputError(f"gh holds no token for {host}; run: gh auth login --hostname {host}")
|
|
188
|
+
return token
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _gh(args: list[str], host: str) -> subprocess.CompletedProcess[str]:
|
|
192
|
+
argv = ["gh", *args]
|
|
193
|
+
try:
|
|
194
|
+
return subprocess.run(argv, capture_output=True, text=True, timeout=TIMEOUT_SECONDS, check=False) # noqa: S603
|
|
195
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
196
|
+
raise InputError(f"cannot run gh to read the token for {host}: {e}") from e
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class Client:
|
|
200
|
+
"""GitHub's GraphQL API at one endpoint, with one token, sent to that endpoint's host alone (canopy-http)."""
|
|
201
|
+
|
|
202
|
+
def __init__(self, url: str, token: str) -> None:
|
|
203
|
+
"""Talk to the endpoint at `url` with `token`."""
|
|
204
|
+
self._url = url
|
|
205
|
+
headers = {
|
|
206
|
+
"Authorization": f"bearer {token}",
|
|
207
|
+
# A PR's `mergeStateStatus` was a preview; asking for it names the preview, which GitHub otherwise ignores.
|
|
208
|
+
"Accept": f"{MERGE_INFO_PREVIEW}, application/json",
|
|
209
|
+
"User-Agent": "canopy-github",
|
|
210
|
+
}
|
|
211
|
+
retry = canopy_http.Retry(pauses=RETRY_PAUSES)
|
|
212
|
+
self._http = canopy_http.Client(url, name="GitHub", headers=headers, retry=retry)
|
|
213
|
+
|
|
214
|
+
def query(self, document: str, variables: Mapping[str, object]) -> Mapping[str, object]:
|
|
215
|
+
"""Send one query or mutation, which GitHub must answer whole.
|
|
216
|
+
|
|
217
|
+
Returns:
|
|
218
|
+
The reply's `data`.
|
|
219
|
+
|
|
220
|
+
Raises:
|
|
221
|
+
GitHubError: GitHub refused it, answered with errors, or could not be reached.
|
|
222
|
+
"""
|
|
223
|
+
reply = self.ask(document, variables)
|
|
224
|
+
if reply.errors:
|
|
225
|
+
raise GitHubError(refusal(reply.errors), certain=True, types=error_types(reply.errors))
|
|
226
|
+
return reply.data
|
|
227
|
+
|
|
228
|
+
def ask(self, document: str, variables: Mapping[str, object], *, retry: bool = True) -> Reply:
|
|
229
|
+
"""Send one query, which GitHub may answer in part: an error about one field leaves the rest of `data`.
|
|
230
|
+
|
|
231
|
+
A query GitHub answers with a server error, or whose reply breaks off, or that GitHub failed to run, is sent
|
|
232
|
+
again, after each of `RETRY_PAUSES`, unless `retry` is false.
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
The reply's `data`, and its errors.
|
|
236
|
+
|
|
237
|
+
Raises:
|
|
238
|
+
ServerError: GitHub answered with a server error, or its reply broke off or is not JSON, or it failed to run
|
|
239
|
+
the query, each time it was sent.
|
|
240
|
+
GitHubError: GitHub refused it whole, or could not be reached.
|
|
241
|
+
"""
|
|
242
|
+
again = retry and _QUERY.match(document) is not None
|
|
243
|
+
request = {"query": document, "variables": dict(variables)}
|
|
244
|
+
try:
|
|
245
|
+
parsed = self._http.json("POST", self._url, body=request, again=again, failed=_failed_to_run)
|
|
246
|
+
except canopy_http.FailedError as e:
|
|
247
|
+
raise ServerError(f"{e} (tried {e.tries} times)" if e.tries > 1 else str(e), certain=False) from e
|
|
248
|
+
except canopy_http.HttpError as e:
|
|
249
|
+
raise GitHubError(str(e), certain=e.certain) from e
|
|
250
|
+
body = obj(parsed, "reply")
|
|
251
|
+
errors = items(body.get("errors"))
|
|
252
|
+
data = body.get("data")
|
|
253
|
+
if errors and not isinstance(data, dict):
|
|
254
|
+
raise GitHubError(refusal(errors), certain=True, types=error_types(errors))
|
|
255
|
+
return Reply(obj(data, "data"), tuple(errors))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _failed_to_run(parsed: object) -> str | None:
|
|
259
|
+
"""What GitHub said of a query it failed to run, as one past its time limit fails, though it answered with a 200.
|
|
260
|
+
|
|
261
|
+
The error is GitHub's, not a refusal of the query or of the token, so the try fails as a server error does: a query
|
|
262
|
+
is sent again, and a mutation may have been carried out. GitHub's words are kept, as they hold its request ID.
|
|
263
|
+
|
|
264
|
+
Args:
|
|
265
|
+
parsed: GitHub's reply, parsed from its JSON.
|
|
266
|
+
|
|
267
|
+
Returns:
|
|
268
|
+
Why the try failed, or None when GitHub ran the query.
|
|
269
|
+
"""
|
|
270
|
+
if not isinstance(parsed, dict):
|
|
271
|
+
return None
|
|
272
|
+
errors = items(obj(parsed, "reply").get("errors"))
|
|
273
|
+
said = [m for e in errors if isinstance(m := e.get("message"), str) and m.startswith(_FAILED_TO_RUN)]
|
|
274
|
+
if not said:
|
|
275
|
+
return None
|
|
276
|
+
why = "; ".join(said)[:_MAX_REPLY]
|
|
277
|
+
return (
|
|
278
|
+
f"GitHub failed to run the query, likely a timeout or a brief outage on its side, not a matter of access: {why}"
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
@dataclass(frozen=True)
|
|
283
|
+
class Reply:
|
|
284
|
+
"""GitHub's answer to one query: its `data`, and the errors that left parts of it out."""
|
|
285
|
+
|
|
286
|
+
data: Mapping[str, object]
|
|
287
|
+
#: Each error as GitHub sent it; one about a field names it in its `path`.
|
|
288
|
+
errors: Sequence[Mapping[str, object]] = ()
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def refusal(errors: Iterable[Mapping[str, object]]) -> str:
|
|
292
|
+
"""What GitHub's errors say, for a `GitHubError`.
|
|
293
|
+
|
|
294
|
+
Returns:
|
|
295
|
+
Their messages, quoted only so far.
|
|
296
|
+
"""
|
|
297
|
+
messages = "; ".join(str(e.get("message")) for e in errors)
|
|
298
|
+
return f"GitHub refused it: {messages[:_MAX_REPLY]}"
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def error_types(errors: Iterable[Mapping[str, object]]) -> tuple[str, ...]:
|
|
302
|
+
"""The types GitHub's errors name, such as `NOT_FOUND`.
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
The types, in order.
|
|
306
|
+
"""
|
|
307
|
+
return tuple(t for e in errors if isinstance(t := e.get("type"), str))
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def client_for(host: str, endpoint_of: Endpoint, token_of: Token) -> Client:
|
|
311
|
+
"""A client for `host`, with its endpoint and token.
|
|
312
|
+
|
|
313
|
+
Returns:
|
|
314
|
+
The client.
|
|
315
|
+
"""
|
|
316
|
+
return Client(endpoint_of(host), token_of(host))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def pages(fetch: Callable[[str | None], Mapping[str, object]]) -> Iterator[Mapping[str, object]]:
|
|
320
|
+
"""Each node of a connection, page by page: `fetch(cursor)` returns one page, `None` for the first.
|
|
321
|
+
|
|
322
|
+
Yields:
|
|
323
|
+
Each node, in order.
|
|
324
|
+
|
|
325
|
+
Raises:
|
|
326
|
+
GitHubError: The pages never end: GitHub sent a page's cursor twice.
|
|
327
|
+
"""
|
|
328
|
+
seen: set[str] = set()
|
|
329
|
+
cursor: str | None = None
|
|
330
|
+
while True:
|
|
331
|
+
page = fetch(cursor)
|
|
332
|
+
yield from items(page.get("nodes"))
|
|
333
|
+
info = obj(page.get("pageInfo"), "pageInfo")
|
|
334
|
+
after = info.get("endCursor")
|
|
335
|
+
if info.get("hasNextPage") is not True or not isinstance(after, str):
|
|
336
|
+
return
|
|
337
|
+
if after in seen:
|
|
338
|
+
raise GitHubError("its pages never end: GitHub sent a page's cursor twice", certain=True)
|
|
339
|
+
seen.add(after)
|
|
340
|
+
cursor = after
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def more(first: Mapping[str, object], fetch: Callable[[str], Mapping[str, object]]) -> Iterator[Mapping[str, object]]:
|
|
344
|
+
"""Each node of a connection whose first page is in hand, the rest fetched by `fetch(cursor)` as `pages` does.
|
|
345
|
+
|
|
346
|
+
Returns:
|
|
347
|
+
The nodes, in order, as `pages` yields them.
|
|
348
|
+
"""
|
|
349
|
+
return pages(lambda after: first if after is None else fetch(after))
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def backward(
|
|
353
|
+
last: Mapping[str, object],
|
|
354
|
+
fetch: Callable[[str], Mapping[str, object]],
|
|
355
|
+
) -> Iterator[list[Mapping[str, object]]]:
|
|
356
|
+
"""Each page of a connection read from its end, its last page in hand and each earlier one fetched by its cursor.
|
|
357
|
+
|
|
358
|
+
Yields:
|
|
359
|
+
Each page's nodes, the newest page first, each page in GitHub's order.
|
|
360
|
+
|
|
361
|
+
Raises:
|
|
362
|
+
GitHubError: The pages never end: GitHub sent a page's cursor twice.
|
|
363
|
+
"""
|
|
364
|
+
seen: set[str] = set()
|
|
365
|
+
page = last
|
|
366
|
+
while True:
|
|
367
|
+
yield items(page.get("nodes"))
|
|
368
|
+
info = obj(page.get("pageInfo"), "pageInfo")
|
|
369
|
+
cursor = info.get("startCursor")
|
|
370
|
+
if info.get("hasPreviousPage") is not True or not isinstance(cursor, str):
|
|
371
|
+
return
|
|
372
|
+
if cursor in seen:
|
|
373
|
+
raise GitHubError("its pages never end: GitHub sent a page's cursor twice", certain=True)
|
|
374
|
+
seen.add(cursor)
|
|
375
|
+
page = fetch(cursor)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def obj(value: object, what: str) -> Mapping[str, object]:
|
|
379
|
+
"""`value` as a JSON object.
|
|
380
|
+
|
|
381
|
+
Returns:
|
|
382
|
+
The object, with string keys.
|
|
383
|
+
|
|
384
|
+
Raises:
|
|
385
|
+
GitHubError: `value` is not an object, so GitHub's reply is not the shape asked for.
|
|
386
|
+
"""
|
|
387
|
+
if not isinstance(value, dict):
|
|
388
|
+
raise GitHubError(f"GitHub's reply has no {what}", certain=False)
|
|
389
|
+
return {str(k): v for k, v in value.items()}
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def items(value: object) -> list[Mapping[str, object]]:
|
|
393
|
+
"""`value` as a JSON array of objects: what is not an object is left out, and anything but an array is empty.
|
|
394
|
+
|
|
395
|
+
Returns:
|
|
396
|
+
The objects.
|
|
397
|
+
"""
|
|
398
|
+
if not isinstance(value, list):
|
|
399
|
+
return []
|
|
400
|
+
return [{str(k): v for k, v in item.items()} for item in value if isinstance(item, dict)]
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def text(value: object) -> str | None:
|
|
404
|
+
"""`value` if it is a string.
|
|
405
|
+
|
|
406
|
+
Returns:
|
|
407
|
+
The string, or None.
|
|
408
|
+
"""
|
|
409
|
+
return value if isinstance(value, str) else None
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def parse_time(value: object) -> datetime | None:
|
|
413
|
+
"""A time as GitHub writes it, `2026-10-18T10:00:00Z`, or as canopy does, in ISO 8601.
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
The time, in UTC when it names no offset; None for anything else.
|
|
417
|
+
"""
|
|
418
|
+
if not isinstance(value, str):
|
|
419
|
+
return None
|
|
420
|
+
try:
|
|
421
|
+
moment = datetime.fromisoformat(value)
|
|
422
|
+
except ValueError:
|
|
423
|
+
return None
|
|
424
|
+
return moment if moment.tzinfo is not None else moment.replace(tzinfo=UTC)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def number(value: object) -> int | None:
|
|
428
|
+
"""`value` as a positive integer: GitHub sends a BigInt id as a string of digits.
|
|
429
|
+
|
|
430
|
+
Returns:
|
|
431
|
+
The integer, or None.
|
|
432
|
+
"""
|
|
433
|
+
if isinstance(value, bool):
|
|
434
|
+
return None
|
|
435
|
+
if isinstance(value, int):
|
|
436
|
+
return value if value > 0 else None
|
|
437
|
+
if isinstance(value, str) and value.isascii() and value.isdigit():
|
|
438
|
+
return int(value) or None
|
|
439
|
+
return None
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def login(author: object) -> str | None:
|
|
443
|
+
"""An author's login as GitHub's REST API names it, so a bot's ends `[bot]`, which GraphQL leaves off.
|
|
444
|
+
|
|
445
|
+
`trust.trusted_reviewers`, the agents, and GitHub's own pages name a bot as `name[bot]`, and match logins in full,
|
|
446
|
+
so a bare `name` from GraphQL would match no entry.
|
|
447
|
+
|
|
448
|
+
Args:
|
|
449
|
+
author: A GraphQL `Actor` as a reply holds it, `{"__typename": ..., "login": ...}`; null for no author.
|
|
450
|
+
|
|
451
|
+
Returns:
|
|
452
|
+
The login; None for content with no author, as a deleted account's has.
|
|
453
|
+
"""
|
|
454
|
+
if not isinstance(author, dict):
|
|
455
|
+
return None
|
|
456
|
+
fields = obj(author, "author")
|
|
457
|
+
found = text(fields.get("login"))
|
|
458
|
+
if found is None:
|
|
459
|
+
return None
|
|
460
|
+
bot = fields.get("__typename") == "Bot" and not found.endswith("[bot]")
|
|
461
|
+
return f"{found}[bot]" if bot else found
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def cut(body: object) -> str:
|
|
465
|
+
"""`body` cut at `MAX_BODY` characters; anything but a string is empty.
|
|
466
|
+
|
|
467
|
+
Returns:
|
|
468
|
+
The text.
|
|
469
|
+
"""
|
|
470
|
+
return body[:MAX_BODY] if isinstance(body, str) else ""
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def read_input(stdin: TextIO) -> Mapping[str, object]:
|
|
474
|
+
"""The one JSON object on `stdin`.
|
|
475
|
+
|
|
476
|
+
Returns:
|
|
477
|
+
The object.
|
|
478
|
+
|
|
479
|
+
Raises:
|
|
480
|
+
InputError: `stdin` is not one JSON object.
|
|
481
|
+
"""
|
|
482
|
+
try:
|
|
483
|
+
parsed: object = json.loads(stdin.read())
|
|
484
|
+
except json.JSONDecodeError as e:
|
|
485
|
+
raise InputError(f"stdin is not JSON: {e}") from e
|
|
486
|
+
if not isinstance(parsed, dict):
|
|
487
|
+
raise InputError("stdin is not a JSON object")
|
|
488
|
+
return {str(k): v for k, v in parsed.items()}
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def emit(stdout: TextIO, line: Mapping[str, object]) -> None:
|
|
492
|
+
"""Print `line` as one JSON line, and flush it, so what was printed survives a kill."""
|
|
493
|
+
stdout.write(json.dumps(dict(line), ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
494
|
+
stdout.flush()
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
@dataclass(frozen=True)
|
|
498
|
+
class Hosts:
|
|
499
|
+
"""How a program reaches a GitHub host: as GitHub's own are reached, unless a test gives its own."""
|
|
500
|
+
|
|
501
|
+
#: A host to its GraphQL endpoint.
|
|
502
|
+
endpoint_of: Endpoint = endpoint
|
|
503
|
+
#: A host to its token.
|
|
504
|
+
token_of: Token = gh_token
|