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.
@@ -0,0 +1,682 @@
1
+ """`canopy-connect-github --repo OWNER/NAME`: one repository's GitHub Issues as canopy's `tracker` source (DESIGN §30).
2
+
3
+ On stdin, one JSON object naming what to observe, each key optional: `query`, in GitHub's search syntax, and
4
+ `tickets`, each `{"key": "GH-12", "comments_since": TIME}`. A ticket's key is `GH-` and its issue's number in the
5
+ repository (DESIGN §17, the `tracker-github` skill). On stdout, one JSON line per observation, in DESIGN §30's shapes,
6
+ as `canopy-connect-jira` prints Jira's:
7
+
8
+ - for each ticket asked and read whole, its `ticket` line, each label with the time its timeline last added it, then a
9
+ `comment` line for each comment created at or after its `comments_since`, or for every comment without one;
10
+ - for each open issue the query returned, read to its last page, its `ticket` line; a PR it returns is passed over;
11
+ - for each issue one of those names as its blocker, its `ticket` line.
12
+
13
+ A ticket's blockers are the issues GitHub's issue dependencies say block it, and those a line of its body names,
14
+ `Blocked by #N`, as a worker orders follow-ups where the dependencies are not there (`tracker-github`). A key names an
15
+ issue of this repository alone, so a ticket an open issue of another repository blocks is not read whole: it stays
16
+ stale, and no dispatch rests on it (DESIGN §7). A closed one blocks nothing, and is left out.
17
+
18
+ Last, an `end` line naming the tickets read whole and, when the query was read to its last page, the open issues it
19
+ returned, in its order. A query that returns an issue of another repository is not read, since no key names it. A
20
+ ticket that could not be read whole prints nothing but its error on stderr, so a cut-off read never looks like a ticket
21
+ with no comments. Nothing is written to GitHub.
22
+
23
+ Exit codes: 0 everything was read; 1 something was not, and the `end` line names what was; 2 the repository, the
24
+ token, or stdin is not usable, and nothing was read.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import operator
30
+ import re
31
+ from collections.abc import Iterable, Mapping, Sequence
32
+ from dataclasses import dataclass, field
33
+ from datetime import UTC, datetime
34
+ from typing import Final, TextIO
35
+
36
+ import click
37
+
38
+ from canopy_github import (
39
+ Client,
40
+ GitHubError,
41
+ Hosts,
42
+ InputError,
43
+ Reply,
44
+ ServerError,
45
+ backward,
46
+ client_for,
47
+ cut,
48
+ emit,
49
+ error_types,
50
+ items,
51
+ login,
52
+ number,
53
+ obj,
54
+ pages,
55
+ parse_time,
56
+ read_input,
57
+ refusal,
58
+ text,
59
+ )
60
+ from canopy_github.repository import MAX_SEARCH
61
+
62
+ #: A ticket's key is this, a hyphen, and its issue's number: issue 12 is `GH-12` (DESIGN §17).
63
+ PREFIX: Final = "GH"
64
+ #: The host `--repo` is on when it names none.
65
+ DEFAULT_HOST: Final = "github.com"
66
+ #: More than any one request needs: canopy asks for the tickets its state block lists.
67
+ MAX_TICKETS: Final = 1000
68
+ #: Issues one query reads: each asks for some 400 nodes (a page each of labels, blockers, label events, and comments).
69
+ BATCH: Final = 25
70
+ #: The most labels or blockers a ticket's line carries: canopy refuses a line with more, so a ticket with more is not
71
+ #: read whole.
72
+ MAX_LIST: Final = 100
73
+ #: A ticket's key as canopy sends one, and as this tracker gives one: a number GraphQL's 32-bit `Int` holds.
74
+ _ASKED: Final = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,99}")
75
+ _KEY: Final = re.compile(rf"{PREFIX}-([1-9][0-9]{{0,8}})")
76
+ #: `--repo`: `OWNER/NAME`, or `HOST/OWNER/NAME` for GitHub Enterprise.
77
+ _REPO: Final = re.compile(
78
+ r"(?:([A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?(?::[0-9]{1,5})?)/)?"
79
+ r"([A-Za-z0-9_.-]{1,100})/([A-Za-z0-9_.-]{1,100})",
80
+ )
81
+ #: A line of an issue's body naming a blocker in the same repository (`tracker-github`).
82
+ _BLOCKED_BY: Final = re.compile(r"^[ \t]*blocked by #([1-9][0-9]{0,8})\b", re.IGNORECASE | re.MULTILINE)
83
+ #: The login GitHub shows for an account since deleted, which no one can hold: a comment with no author is its.
84
+ _GHOST: Final = "ghost"
85
+
86
+ _TICKET: Final = """
87
+ fragment Ticket on Issue {
88
+ number title body state updatedAt
89
+ repository { nameWithOwner }
90
+ labels(first: 100) { pageInfo { hasNextPage } nodes { name } }
91
+ blockedBy(first: 100) { pageInfo { hasNextPage } nodes { number state repository { nameWithOwner } } }
92
+ }
93
+ """
94
+
95
+ #: What an asked ticket is read with besides: read from the newest, as the newest label event and comment matter most.
96
+ _LABELED: Final = "pageInfo { hasPreviousPage startCursor } nodes { ... on LabeledEvent { createdAt label { name } } }"
97
+ _COMMENTS: Final = (
98
+ "pageInfo { hasPreviousPage startCursor } nodes { fullDatabaseId createdAt body author { __typename login } }"
99
+ )
100
+ _HISTORY: Final = f"""
101
+ fragment History on Issue {{
102
+ timelineItems(itemTypes: [LABELED_EVENT], last: 100) {{ {_LABELED} }}
103
+ comments(last: 100) {{ {_COMMENTS} }}
104
+ }}
105
+ """
106
+
107
+ _MORE_LABELED: Final = f"""
108
+ query Labeled($owner: String!, $name: String!, $number: Int!, $before: String) {{
109
+ repository(owner: $owner, name: $name) {{
110
+ issue(number: $number) {{ timelineItems(itemTypes: [LABELED_EVENT], last: 100, before: $before) {{ {_LABELED} }} }}
111
+ }}
112
+ }}
113
+ """
114
+
115
+ _MORE_COMMENTS: Final = f"""
116
+ query IssueComments($owner: String!, $name: String!, $number: Int!, $before: String) {{
117
+ repository(owner: $owner, name: $name) {{
118
+ issue(number: $number) {{ comments(last: 100, before: $before) {{ {_COMMENTS} }} }}
119
+ }}
120
+ }}
121
+ """
122
+
123
+ _SEARCH: Final = (
124
+ """
125
+ query IssueSearch($query: String!, $after: String) {
126
+ search(query: $query, type: ISSUE, first: 100, after: $after) {
127
+ issueCount
128
+ pageInfo { hasNextPage endCursor }
129
+ nodes { __typename ...Ticket }
130
+ }
131
+ }
132
+ """
133
+ + _TICKET
134
+ )
135
+
136
+
137
+ @dataclass(frozen=True)
138
+ class Repository:
139
+ """The repository whose issues are the tickets, as `--repo` names it."""
140
+
141
+ host: str
142
+ owner: str
143
+ name: str
144
+
145
+ @property
146
+ def full(self) -> str:
147
+ """`OWNER/NAME`, lowercased, as GitHub compares a repository's name.
148
+
149
+ Returns:
150
+ The name.
151
+ """
152
+ return f"{self.owner}/{self.name}".lower()
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class Asked:
157
+ """A ticket the request names, its issue's number, and the time of the newest of its comments canopy holds."""
158
+
159
+ key: str
160
+ number: int | None
161
+ since: datetime | None = None
162
+
163
+
164
+ @dataclass(frozen=True)
165
+ class Request:
166
+ """What one run is asked to observe: the query, when asked, and the tickets."""
167
+
168
+ query: str | None
169
+ tickets: Sequence[Asked]
170
+
171
+
172
+ def observe(repo: str, hosts: Hosts, stdin: TextIO, stdout: TextIO) -> int:
173
+ """Read the request on `stdin`, and print what the repository's issues hold of it, the `end` line last.
174
+
175
+ Returns:
176
+ The exit code, as the module says.
177
+ """
178
+ try:
179
+ repository = parse_repo(repo)
180
+ request = _request(read_input(stdin))
181
+ client = client_for(repository.host, hosts.endpoint_of, hosts.token_of)
182
+ except InputError as e:
183
+ _say(str(e))
184
+ return 2
185
+ reader = _Reader(client, repository, stdout)
186
+ query = reader.read(request)
187
+ end: dict[str, object] = {"kind": "end", "tickets": reader.whole}
188
+ if query is not None:
189
+ end["query"] = query
190
+ emit(stdout, end)
191
+ return 1 if reader.failed else 0
192
+
193
+
194
+ def parse_repo(value: str) -> Repository:
195
+ """Read `--repo`: `OWNER/NAME`, on github.com, or `HOST/OWNER/NAME`.
196
+
197
+ Returns:
198
+ The repository.
199
+
200
+ Raises:
201
+ InputError: `value` is not such a name.
202
+ """
203
+ match = _REPO.fullmatch(value)
204
+ if match is None or match[3] in {".", ".."}:
205
+ raise InputError(f"--repo {value!r} is not OWNER/NAME, or HOST/OWNER/NAME")
206
+ host, owner, name = match.groups()
207
+ return Repository((host or DEFAULT_HOST).lower(), owner, name)
208
+
209
+
210
+ def _request(raw: Mapping[str, object]) -> Request:
211
+ """Read the request: a key canopy sends another kind of source is not this one's, and is passed over.
212
+
213
+ Returns:
214
+ The request, each ticket once, in the order given; a key this tracker gives no issue has no number.
215
+
216
+ Raises:
217
+ InputError: The query or a ticket is not usable.
218
+ """
219
+ query = raw.get("query")
220
+ if query is not None and not (isinstance(query, str) and query.strip()):
221
+ raise InputError("the query must be GitHub's search syntax, a string that is not blank")
222
+ tickets = raw.get("tickets", [])
223
+ if not isinstance(tickets, list):
224
+ raise InputError('stdin\'s tickets must be a list: {"tickets": [{"key": "GH-1"}]}')
225
+ if len(tickets) > MAX_TICKETS:
226
+ raise InputError(f"stdin names {len(tickets)} tickets; at most {MAX_TICKETS} a read")
227
+ asked: dict[str, Asked] = {}
228
+ for ticket in tickets:
229
+ fields = obj(ticket, "ticket") if isinstance(ticket, dict) else {}
230
+ key = fields.get("key")
231
+ if not isinstance(key, str) or not _ASKED.fullmatch(key):
232
+ raise InputError(f"{key!r} is not a ticket's key")
233
+ since = fields.get("comments_since")
234
+ moment = None if since is None else parse_time(since)
235
+ if since is not None and moment is None:
236
+ raise InputError(f"{key}'s comments_since {since!r} is not an ISO 8601 time")
237
+ match = _KEY.fullmatch(key)
238
+ asked.setdefault(key, Asked(key, None if match is None else int(match[1]), moment))
239
+ return Request(query if isinstance(query, str) else None, list(asked.values()))
240
+
241
+
242
+ @dataclass
243
+ class _Reader:
244
+ """One run's reads: what it printed whole, the blockers left to read, and whether anything was not read."""
245
+
246
+ client: Client
247
+ repository: Repository
248
+ stdout: TextIO
249
+ #: The tickets printed whole, in the order printed.
250
+ whole: list[str] = field(default_factory=list[str])
251
+ #: The issues the tickets printed name as blockers, in the order named.
252
+ blockers: dict[int, None] = field(default_factory=dict[int, None])
253
+ #: The tickets that could not be read whole: neither the query nor a blocker prints one asked without its comments.
254
+ missed: set[str] = field(default_factory=set[str])
255
+ failed: bool = False
256
+
257
+ def read(self, request: Request) -> list[str] | None:
258
+ """Read and print the tickets asked, then the query's, then the blockers any of them names.
259
+
260
+ Returns:
261
+ The open tickets the query returned, in its order; None when it was not asked or not read to the end.
262
+ """
263
+ self._asked(request.tickets)
264
+ query = None if request.query is None else self._query(request.query)
265
+ self._blockers()
266
+ return query
267
+
268
+ def _asked(self, asked: Sequence[Asked]) -> None:
269
+ """Read each ticket asked whole, with its labels' times and its comments, and print it."""
270
+ numbered: list[tuple[Asked, int]] = []
271
+ for ticket in asked:
272
+ if ticket.number is None:
273
+ self.missed.add(ticket.key)
274
+ self._miss(ticket.key, f"it is not a key of GitHub Issues, {PREFIX}- and the issue's number")
275
+ else:
276
+ numbered.append((ticket, ticket.number))
277
+ found = self._fetch([n for _, n in numbered], history=True)
278
+ for ticket, issue_number in numbered:
279
+ try:
280
+ issue = self._own(found[issue_number])
281
+ labels = self._label_times(issue_number, issue)
282
+ lines = [self._ticket(issue, labels), *self._comments(ticket, issue_number, issue)]
283
+ except GitHubError as e:
284
+ self.missed.add(ticket.key)
285
+ self._miss(ticket.key, e)
286
+ continue
287
+ self._print(ticket.key, lines, issue)
288
+
289
+ def _query(self, query: str) -> list[str] | None:
290
+ """Run the query to its last page, printing each open issue it returns that was not printed already.
291
+
292
+ Returns:
293
+ The open tickets it returned, in its order; None when it could not be read to the end.
294
+ """
295
+
296
+ def fetch(after: str | None) -> Mapping[str, object]:
297
+ found = obj(self.client.query(_SEARCH, {"query": query, "after": after}).get("search"), "search")
298
+ total = found.get("issueCount")
299
+ if isinstance(total, int) and total > MAX_SEARCH:
300
+ raise GitHubError(f"it matches {total}, more than the {MAX_SEARCH} GitHub returns", certain=True)
301
+ return found
302
+
303
+ keys: dict[str, None] = {}
304
+ try:
305
+ for issue in pages(fetch):
306
+ if issue.get("__typename") != "Issue":
307
+ continue
308
+ where = _where(issue)
309
+ if where.lower() != self.repository.full:
310
+ narrow = f"repo:{self.repository.owner}/{self.repository.name}"
311
+ self._miss(
312
+ "the query",
313
+ f"it returned {where}#{issue.get('number')}, which no key names; narrow it with {narrow}",
314
+ )
315
+ return None
316
+ key = _key(_number(issue))
317
+ if _state(issue) != "open" or key in keys:
318
+ continue
319
+ keys[key] = None
320
+ if key not in self.whole and key not in self.missed:
321
+ self._print_one(key, issue, follow=True)
322
+ except GitHubError as e:
323
+ self._miss("the query", e)
324
+ return None
325
+ return list(keys)
326
+
327
+ def _blockers(self) -> None:
328
+ """Read and print each blocker not printed already. A blocker's own blockers are not followed."""
329
+ pending = [n for n in self.blockers if _key(n) not in self.whole and _key(n) not in self.missed]
330
+ found = self._fetch(pending, history=False)
331
+ for issue_number in pending:
332
+ try:
333
+ issue = self._own(found[issue_number])
334
+ except GitHubError as e:
335
+ self._miss(f"blocker {_key(issue_number)}", e)
336
+ continue
337
+ self._print_one(_key(issue_number), issue, follow=False)
338
+
339
+ def _print_one(self, key: str, issue: Mapping[str, object], *, follow: bool) -> None:
340
+ """Print a ticket's line alone, as the query and a blocker are read; one that cannot be printed is named."""
341
+ try:
342
+ line = self._ticket(issue, {})
343
+ except GitHubError as e:
344
+ self.missed.add(key)
345
+ self._miss(key if follow else f"blocker {key}", e)
346
+ return
347
+ self._print(key, [line], issue if follow else None)
348
+
349
+ def _fetch(self, numbers: Sequence[int], *, history: bool) -> dict[int, Mapping[str, object] | GitHubError]:
350
+ """Fetch each issue, `BATCH` to a query, with its history when asked.
351
+
352
+ A query of many issues GitHub answers with a server error is read again in halves rather than sent again
353
+ whole, as one too heavy to answer in time would fail each time; a query of one issue is sent again.
354
+
355
+ Returns:
356
+ Each issue, or why it was not read, by its number.
357
+ """
358
+ found: dict[int, Mapping[str, object] | GitHubError] = {}
359
+ for start in range(0, len(numbers), BATCH):
360
+ chunk = numbers[start : start + BATCH]
361
+ found |= self._read(chunk, self._ask(chunk, history=history), history=history)
362
+ return found
363
+
364
+ def _ask(self, numbers: Sequence[int], *, history: bool) -> Reply | GitHubError:
365
+ variables: dict[str, object] = {"owner": self.repository.owner, "name": self.repository.name}
366
+ variables |= {f"k{i}": n for i, n in enumerate(numbers)}
367
+ try:
368
+ return self.client.ask(_batch(len(numbers), history=history), variables, retry=len(numbers) == 1)
369
+ except GitHubError as e:
370
+ return e
371
+
372
+ def _read(
373
+ self,
374
+ numbers: Sequence[int],
375
+ reply: Reply | GitHubError,
376
+ *,
377
+ history: bool,
378
+ split: bool = True,
379
+ ) -> dict[int, Mapping[str, object] | GitHubError]:
380
+ """Each of `numbers` from the reply to the query that read them, or, for a server error, from its halves'.
381
+
382
+ When both halves fail, GitHub is failing whatever it is asked, and neither is split again.
383
+
384
+ Returns:
385
+ Each issue, or why it was not read, by its number.
386
+ """
387
+ if split and isinstance(reply, ServerError) and len(numbers) > 1:
388
+ middle = len(numbers) // 2
389
+ halves = (numbers[:middle], numbers[middle:])
390
+ replies = [self._ask(half, history=history) for half in halves]
391
+ again = not all(isinstance(r, GitHubError) for r in replies)
392
+ found: dict[int, Mapping[str, object] | GitHubError] = {}
393
+ for half, half_reply in zip(halves, replies, strict=True):
394
+ found |= self._read(half, half_reply, history=history, split=again)
395
+ return found
396
+ if isinstance(reply, GitHubError):
397
+ return dict.fromkeys(numbers, reply)
398
+ return {n: _aliased(reply, f"i{i}") for i, n in enumerate(numbers)}
399
+
400
+ def _own(self, issue: Mapping[str, object] | GitHubError) -> Mapping[str, object]:
401
+ """The issue, once it is this repository's: one GitHub returned from another was moved there.
402
+
403
+ Returns:
404
+ The issue.
405
+
406
+ Raises:
407
+ GitHubError: It was not read, or it is another repository's.
408
+ """
409
+ if isinstance(issue, GitHubError):
410
+ raise issue
411
+ where = _where(issue)
412
+ if where.lower() != self.repository.full:
413
+ raise GitHubError(f"it was moved to {where}, where no key names it", certain=True)
414
+ return issue
415
+
416
+ def _ticket(self, issue: Mapping[str, object], added: Mapping[str, datetime]) -> dict[str, object]:
417
+ """A ticket's line, from the issue as GitHub sent it and the times its labels were added.
418
+
419
+ Returns:
420
+ The line.
421
+
422
+ Raises:
423
+ GitHubError: The issue has no number or state, more labels or blockers than its line may carry, or an open
424
+ blocker in another repository.
425
+ """
426
+ labels = _labels(issue)
427
+ line: dict[str, object] = {
428
+ "kind": "ticket",
429
+ "key": _key(_number(issue)),
430
+ "title": " ".join((text(issue.get("title")) or "").split()) or "(no title)",
431
+ "body": cut(issue.get("body")).strip(),
432
+ "state": _state(issue),
433
+ "labels": [
434
+ {"name": label, **({"added_at": _format(added[label])} if label in added else {})} for label in labels
435
+ ],
436
+ "blockers": [_key(n) for n in self._blockers_of(issue)],
437
+ }
438
+ updated = parse_time(issue.get("updatedAt"))
439
+ if updated is not None:
440
+ line["updated_at"] = _format(updated)
441
+ return line
442
+
443
+ def _blockers_of(self, issue: Mapping[str, object]) -> list[int]:
444
+ """The issues that block this one: its dependencies' "blocked by", then its body's `Blocked by #N` lines.
445
+
446
+ Returns:
447
+ Their numbers, each once, in that order, the issue's own left out.
448
+
449
+ Raises:
450
+ GitHubError: It has more than its line may carry, or an open one is another repository's.
451
+ """
452
+ dependencies = obj(issue.get("blockedBy"), "blockedBy")
453
+ if obj(dependencies.get("pageInfo"), "pageInfo").get("hasNextPage") is True:
454
+ raise GitHubError(f"it is blocked by more than {MAX_LIST} issues", certain=True)
455
+ found: dict[int, None] = {}
456
+ for node in items(dependencies.get("nodes")):
457
+ where, blocker = _where(node), _number(node)
458
+ if where.lower() == self.repository.full:
459
+ found[blocker] = None
460
+ elif node.get("state") != "CLOSED":
461
+ why = f"it is blocked by {where}#{blocker}, open in a repository no key names"
462
+ raise GitHubError(why, certain=True)
463
+ for match in _BLOCKED_BY.finditer(text(issue.get("body")) or ""):
464
+ found.setdefault(int(match[1]))
465
+ found.pop(_number(issue), None)
466
+ if len(found) > MAX_LIST:
467
+ raise GitHubError(f"it is blocked by more than {MAX_LIST} issues", certain=True)
468
+ return list(found)
469
+
470
+ def _label_times(self, issue_number: int, issue: Mapping[str, object]) -> dict[str, datetime]:
471
+ """When the timeline last added each label the issue has; a label it never added has none.
472
+
473
+ Returns:
474
+ Each label's time, by name.
475
+ """
476
+ labels = set(_labels(issue))
477
+ added: dict[str, datetime] = {}
478
+ if not labels:
479
+ return added
480
+
481
+ def before(cursor: str) -> Mapping[str, object]:
482
+ return obj(self._more(_MORE_LABELED, issue_number, cursor).get("timelineItems"), "timelineItems")
483
+
484
+ for page in backward(obj(issue.get("timelineItems"), "timelineItems"), before):
485
+ for event in page:
486
+ label = event.get("label")
487
+ name = text(obj(label, "label").get("name")) if isinstance(label, dict) else None
488
+ moment = parse_time(event.get("createdAt"))
489
+ if name in labels and moment is not None and (name not in added or added[name] < moment):
490
+ added[name] = moment
491
+ if labels <= added.keys():
492
+ break
493
+ return added
494
+
495
+ def _comments(self, ticket: Asked, issue_number: int, issue: Mapping[str, object]) -> list[dict[str, object]]:
496
+ """Read the ticket's comments created at or after its `since`, from the newest, stopping at an older one.
497
+
498
+ Returns:
499
+ The comments' lines, oldest first.
500
+
501
+ Raises:
502
+ GitHubError: A page could not be read, or a comment has no id or time.
503
+ """
504
+
505
+ def before(cursor: str) -> Mapping[str, object]:
506
+ return obj(self._more(_MORE_COMMENTS, issue_number, cursor).get("comments"), "comments")
507
+
508
+ found: list[tuple[datetime, dict[str, object]]] = []
509
+ for page in backward(obj(issue.get("comments"), "comments"), before):
510
+ lines = [_comment(ticket.key, node) for node in page]
511
+ found.extend(c for c in lines if ticket.since is None or c[0] >= ticket.since)
512
+ if ticket.since is not None and any(c[0] < ticket.since for c in lines):
513
+ break
514
+ return [line for _, line in sorted(found, key=operator.itemgetter(0))]
515
+
516
+ def _more(self, document: str, issue_number: int, cursor: str) -> Mapping[str, object]:
517
+ """One more page of an issue's connection, read from its end.
518
+
519
+ Returns:
520
+ The issue's node.
521
+
522
+ Raises:
523
+ GitHubError: GitHub refused the page, could not be reached, or no longer has the issue.
524
+ """
525
+ variables = {
526
+ "owner": self.repository.owner,
527
+ "name": self.repository.name,
528
+ "number": issue_number,
529
+ "before": cursor,
530
+ }
531
+ repository = obj(self.client.query(document, variables).get("repository"), "repository")
532
+ return obj(repository.get("issue"), f"issue {_key(issue_number)}")
533
+
534
+ def _print(self, key: str, lines: Iterable[Mapping[str, object]], issue: Mapping[str, object] | None) -> None:
535
+ """Print a ticket read whole, and note its blockers to read, unless it is a blocker itself (`issue` None)."""
536
+ for line in lines:
537
+ emit(self.stdout, line)
538
+ self.whole.append(key)
539
+ if issue is not None:
540
+ for blocker in self._blockers_of(issue):
541
+ self.blockers.setdefault(blocker)
542
+
543
+ def _miss(self, what: str, why: object) -> None:
544
+ self.failed = True
545
+ _say(f"cannot read {what}: {why}")
546
+
547
+
548
+ def _batch(count: int, *, history: bool) -> str:
549
+ """The query that reads `count` issues of one repository, each under its alias, its number a variable.
550
+
551
+ Returns:
552
+ The query.
553
+ """
554
+ params = "".join(f", $k{i}: Int!" for i in range(count))
555
+ spread = "...Ticket ...History" if history else "...Ticket"
556
+ fields = "\n".join(f" i{i}: issue(number: $k{i}) {{ {spread} }}" for i in range(count))
557
+ fragments = _TICKET + (_HISTORY if history else "")
558
+ head = f"query Issues($owner: String!, $name: String!{params})"
559
+ return f"{head} {{\n repository(owner: $owner, name: $name) {{\n{fields}\n }}\n}}\n{fragments}"
560
+
561
+
562
+ def _aliased(reply: Reply, alias: str) -> Mapping[str, object] | GitHubError:
563
+ """The issue under `alias` in a batch's reply, or why it is not there.
564
+
565
+ Returns:
566
+ The issue's node; or the errors about it, or about no one issue; or, when GitHub returned none, an error.
567
+ """
568
+ errors = [e for e in reply.errors if _about(e, alias)]
569
+ if errors:
570
+ return GitHubError(refusal(errors), certain=True, types=error_types(errors))
571
+ repository = reply.data.get("repository")
572
+ issue = obj(repository, "repository").get(alias) if isinstance(repository, dict) else None
573
+ if not isinstance(issue, dict):
574
+ return GitHubError("GitHub did not return it: deleted, or not visible to you", certain=True)
575
+ return obj(issue, "issue")
576
+
577
+
578
+ def _about(error: Mapping[str, object], alias: str) -> bool:
579
+ # An error with no path, or about the repository, is about every issue in the query.
580
+ path = error.get("path")
581
+ return not isinstance(path, list) or len(path) < 2 or path[1] == alias # noqa: PLR2004
582
+
583
+
584
+ def _key(issue_number: int) -> str:
585
+ return f"{PREFIX}-{issue_number}"
586
+
587
+
588
+ def _number(issue: Mapping[str, object]) -> int:
589
+ found = number(issue.get("number"))
590
+ if found is None:
591
+ raise GitHubError("GitHub sent an issue with no number", certain=True)
592
+ return found
593
+
594
+
595
+ def _where(issue: Mapping[str, object]) -> str:
596
+ """The repository an issue is in, `OWNER/NAME`, as GitHub names it.
597
+
598
+ Returns:
599
+ The name.
600
+
601
+ Raises:
602
+ GitHubError: GitHub named none.
603
+ """
604
+ repository = issue.get("repository")
605
+ where = text(obj(repository, "repository").get("nameWithOwner")) if isinstance(repository, dict) else None
606
+ if where is None:
607
+ raise GitHubError(f"GitHub sent issue #{issue.get('number')} with no repository", certain=True)
608
+ return where
609
+
610
+
611
+ def _state(issue: Mapping[str, object]) -> str:
612
+ """Whether the issue is closed, whatever it was closed as (`tracker-github`).
613
+
614
+ Returns:
615
+ `closed` or `open`.
616
+
617
+ Raises:
618
+ GitHubError: The issue has no state.
619
+ """
620
+ match issue.get("state"):
621
+ case "OPEN":
622
+ return "open"
623
+ case "CLOSED":
624
+ return "closed"
625
+ case state:
626
+ raise GitHubError(f"issue #{issue.get('number')} has no state an issue has: {state!r}", certain=True)
627
+
628
+
629
+ def _labels(issue: Mapping[str, object]) -> list[str]:
630
+ """The issue's labels' names.
631
+
632
+ Returns:
633
+ The names, in GitHub's order.
634
+
635
+ Raises:
636
+ GitHubError: It has more than its line may carry.
637
+ """
638
+ labels = obj(issue.get("labels"), "labels")
639
+ if obj(labels.get("pageInfo"), "pageInfo").get("hasNextPage") is True:
640
+ raise GitHubError(f"it has more than {MAX_LIST} labels", certain=True)
641
+ return [name for node in items(labels.get("nodes")) if (name := text(node.get("name"))) is not None]
642
+
643
+
644
+ def _comment(key: str, node: Mapping[str, object]) -> tuple[datetime, dict[str, object]]:
645
+ """A comment's line, and its time to order it by. Its author is their login (`tracker-github`).
646
+
647
+ Returns:
648
+ The time and the line.
649
+
650
+ Raises:
651
+ GitHubError: The comment has no id or no time.
652
+ """
653
+ id_ = number(node.get("fullDatabaseId"))
654
+ moment = parse_time(node.get("createdAt"))
655
+ if id_ is None or moment is None:
656
+ raise GitHubError(f"a comment on {key} has no id or time", certain=True)
657
+ line: dict[str, object] = {
658
+ "kind": "comment",
659
+ "ticket": key,
660
+ "id": str(id_),
661
+ "author": _author(node.get("author")),
662
+ "time": _format(moment),
663
+ "body": cut(node.get("body")),
664
+ }
665
+ return moment, line
666
+
667
+
668
+ def _author(author: object) -> str:
669
+ """A comment's author's login: a bot's ends `[bot]`, as GitHub's REST API names it, so it is never a replier.
670
+
671
+ Returns:
672
+ The login; a deleted account's is `ghost`.
673
+ """
674
+ return login(author) or _GHOST
675
+
676
+
677
+ def _format(moment: datetime) -> str:
678
+ return moment.astimezone(UTC).isoformat()
679
+
680
+
681
+ def _say(message: str) -> None:
682
+ click.echo(f"canopy-connect-github: {message}", err=True)